Skip to content

Commit

Permalink
embed graphql and resolve local running csor violation issue
Browse files Browse the repository at this point in the history
  • Loading branch information
zhaozixiao committed Dec 12, 2021
1 parent 1707dc3 commit bfabccd
Show file tree
Hide file tree
Showing 10 changed files with 94 additions and 20 deletions.
11 changes: 11 additions & 0 deletions todo-web/.vscode/launch.json
@@ -0,0 +1,11 @@
{
"configurations": [
{
"command": "yarn run start",
"name": "Run yarn start",
"request": "launch",
"type": "node-terminal"
}

]
}
2 changes: 1 addition & 1 deletion todo-web/package.json
Expand Up @@ -17,7 +17,7 @@
"scripts": {
"start": "yarn run relay && react-scripts start",
"build": "yarn run relay && react-scripts build",
"relay": "yarn run relay-compiler --schema schema.graphql --src ./src/ --watchman false $@",
"relay": "yarn run relay-compiler --schema schema.graphql --src ./src/ --extensions=js --watchman false $@",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
Expand Down
62 changes: 45 additions & 17 deletions todo-web/src/App.js
@@ -1,22 +1,52 @@
import React, { useState } from "react";
import React, { useState, useEffect } from "react";
import fetchGraphQL from './fetchGraphQL';
import { nanoid } from "nanoid";
import Form from "./components/Form";
import FilterButton from "./components/FilterButton";
import Todo from "./components/Todo";

function App(props) {
const [tasks, setTasks] = useState(props.tasks);
const taskList = tasks.map(task => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
toggleTaskCompleted={toggleTaskCompleted}
deleteTask={deleteTask}
editTask={editTask}
/>
));
const [tasks, setTasks] = useState(null);
const [headingText, setHeadingText] = useState(null);
useEffect(() => {
let isMounted = true;
fetchGraphQL(`
query {
allTodos {
id
reference
description
}
}
`).then(response => {
// Avoid updating state if the component unmounted before the fetch completes
if (!isMounted) {
return;
}
console.log(response.data.allTodos);
const taskList = response.data.allTodos.map(task => (
<Todo
id={task.id || "todo-" + nanoid()}
name={task.description}
completed={task.completed || false}
key={task.id || nanoid()}
toggleTaskCompleted={toggleTaskCompleted}
deleteTask={deleteTask}
editTask={editTask}
/>
));
setTasks(taskList);
const tasksNoun = taskList.length !== 1 ? 'tasks' : 'task';
setHeadingText(`${taskList.length} ${tasksNoun} remaining`);
console.log(headingText);
}).catch(error => {
console.error(error);
});

return () => {
isMounted = false;
};
}, [fetchGraphQL]);
function addTask(name) {
const newTask = { id: "todo-" + nanoid(), name: name, completed: false };
setTasks([...tasks, newTask]);
Expand Down Expand Up @@ -51,8 +81,6 @@ function App(props) {
setTasks(editedTaskList);
console.log(editedTaskList);
}
const tasksNoun = taskList.length !== 1 ? 'tasks' : 'task';
const headingText = `${taskList.length} ${tasksNoun} remaining`;
return (
<div className="todoapp stack-large">
<h1>TodoMatic</h1>
Expand All @@ -63,14 +91,14 @@ function App(props) {
<FilterButton />
</div>
<h2 id="list-heading">
{headingText}
{headingText != null? headingText : "Loading"}
</h2>
<ul
role="list"
className="todo-list stack-large stack-exception"
aria-labelledby="list-heading"
>
{taskList}
{tasks != null? tasks : "Loading"}
</ul>
</div>
);
Expand Down
16 changes: 16 additions & 0 deletions todo-web/src/RelayEnvironment.js
@@ -0,0 +1,16 @@
// your-app-name/src/RelayEnvironment.js
import {Environment, Network, RecordSource, Store} from 'relay-runtime';
import fetchGraphQL from './fetchGraphQL';

// Relay passes a "params" object with the query name and text. So we define a helper function
// to call our fetchGraphQL utility with params.text.
async function fetchRelay(params, variables) {
console.log(`fetching query ${params.name} with ${JSON.stringify(variables)}`);
return fetchGraphQL(params.text, variables);
}

// Export a singleton instance of Relay Environment configured with our network function:
export default new Environment({
network: Network.create(fetchRelay),
store: new Store(new RecordSource()),
});
2 changes: 1 addition & 1 deletion todo-web/src/fetchGraphQL.js
@@ -1,6 +1,6 @@
async function fetchGraphQL(text, variables) {
// fetch data from the rails server
const response = await fetch('http://localhost:3000/graphql', {
const response = await fetch('http://localhost:3001/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand Down
2 changes: 1 addition & 1 deletion todo-web/src/index.js
Expand Up @@ -10,7 +10,7 @@ const DATA = [
{ id: "todo-2", name: "Repeat", completed: false }
];

ReactDOM.render(<App tasks={DATA} />, document.getElementById("root"));
ReactDOM.render(<App />, document.getElementById("root"));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
Expand Down
2 changes: 2 additions & 0 deletions todoItems/Gemfile
Expand Up @@ -30,6 +30,8 @@ gem 'bootsnap', '>= 1.4.4', require: false

gem "graphql", '~> 1.13.0'

gem 'rack-cors'

group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
Expand Down
3 changes: 3 additions & 0 deletions todoItems/Gemfile.lock
Expand Up @@ -116,6 +116,8 @@ GEM
nio4r (~> 2.0)
racc (1.6.0)
rack (2.2.3)
rack-cors (1.1.1)
rack (>= 2.0.0)
rack-mini-profiler (2.3.3)
rack (>= 1.2.0)
rack-proxy (0.7.0)
Expand Down Expand Up @@ -219,6 +221,7 @@ DEPENDENCIES
listen (~> 3.3)
pg (~> 1.1)
puma (~> 5.0)
rack-cors
rack-mini-profiler (~> 2.0)
rails (~> 6.1.4, >= 6.1.4.1)
sass-rails (>= 6)
Expand Down
6 changes: 6 additions & 0 deletions todoItems/config/application.rb
Expand Up @@ -18,5 +18,11 @@ class Application < Rails::Application
#
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
end
end
8 changes: 8 additions & 0 deletions todoItems/config/initializers/cors.rb
@@ -0,0 +1,8 @@
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end

0 comments on commit bfabccd

Please sign in to comment.