I have a component with create a blog. It works fine and navigates me to the home after adding the new blog object in the database, but I have to refresh the page to be able to see the updated data. So how can I see the updated blogs after navigation without refreshing the page?
JavaScript
x
148
148
1
import { useState } from "react";
2
import { useNavigate } from "react-router-dom";
3
4
export const Create = () => {
5
const [title, setTitle] = useState("");
6
const [body, setbody] = useState("");
7
const [author, setAuthor] = useState("mario");
8
const [isPending, setPending] = useState(false);
9
const nav = useNavigate();
10
11
const newBlog = { title, body, author };
12
13
const handelSubmit = (e) => {
14
e.preventDefault();
15
console.log(title);
16
console.log(body);
17
console.log(author);
18
19
setPending(true);
20
21
fetch("http://localhost:3001/blogs", {
22
method: "POST",
23
headers: { "Content-Type": "application/json" },
24
body: JSON.stringify(newBlog),
25
}).then(() => {
26
console.log("newBlog Added");
27
28
setPending(false);
29
30
nav("/");
31
});
32
console.log(newBlog);
33
};
34
35
return (
36
<div className="create">
37
<h2>Add a New Blog</h2>
38
<form onSubmit={handelSubmit}>
39
<label htmlFor="">Blog title:</label>
40
<input
41
type="text"
42
required
43
value={title}
44
onChange={(e) => setTitle(e.target.value)}
45
/>
46
<label htmlFor="">Blog Body:</label>
47
<textarea
48
required
49
value={body}
50
onChange={(e) => setbody(e.target.value)}
51
></textarea>
52
53
<label htmlFor="">Blog author:</label>
54
<select value={author} onChange={(e) => setAuthor(e.target.value)}>
55
<option value="mario">Mario</option>
56
<option value="magdy">Magdy</option>
57
</select>
58
{!isPending && <button>Add Blog</button>}
59
{isPending && <button disabled>Adding Blog</button>}
60
</form>
61
</div>
62
);
63
};
64
65
//Home component implementation
66
import React from "react";
67
import Blog from "./../blog/Blog";
68
69
export const Home = () => {
70
// const { data, flag, error } = useFetch("http://localhost:3001/blogs");
71
const [blogs, setBlogs] = useState(null);
72
const [flag, setFlag] = useState(true);
73
const [error, setError] = useState(null);
74
75
76
useEffect(() => {
77
fetch("http://localhost:3001/blogs")
78
.then((res) => {
79
if (!res.ok) {
80
throw Error("Error in the API");
81
}
82
return res.json();
83
})
84
.then((data) => {
85
console.log(data);
86
setBlogs(data);
87
setFlag(!flag);
88
})
89
.catch((e) => {
90
console.log(e.message);
91
setError(e.message);
92
setFlag(!flag);
93
});
94
return () => {};
95
}, []);
96
97
return (
98
<div className="home">
99
{blogs && <Blog blogs={blogs} title="All Blogs" />}
100
{flag && <p>Loading</p>}
101
{error !== null && <p>{error}</p>}
102
</div>
103
);
104
};
105
106
107
//Blog component implementation
108
109
import React from "react";
110
import { Link, Route, Routes } from "react-router-dom";
111
import { BlogDetails } from "../BlogDetails/BlogDetails";
112
import { Create } from "../create/Create";
113
114
import { Error } from "../Notfound/Error";
115
116
function Blog({ blogs, title }) {
117
118
return (
119
<Routes>
120
<Route
121
path="/"
122
element={
123
<div>
124
<h2>{title}</h2>
125
{blogs.map((blog) => {
126
return (
127
<div className="blog" key={blog.id}>
128
<Link to={`blogs/${blog.id}`}>
129
<h3>{blog.title}</h3>
130
<p>{blog.body}</p>
131
<h6>Written By {blog.author}</h6>
132
</Link>
133
</div>
134
);
135
})}
136
</div>
137
}
138
></Route>
139
<Route path="/create" element={<Create />}></Route>
140
<Route path="/blogs/:id" element={<BlogDetails />}></Route>
141
<Route path="*" element={<Error />}></Route>
142
</Routes>
143
);
144
}
145
146
export default Blog;
147
148
Advertisement
Answer
In order to update the blogs
state, which is declared at the main point of the application, which is, for example, App.jsx
, you must pass the state blogs
and the set-state-action setBlogs
as properties to the child component. For example:
The state in App.jsx
:
JavaScript
1
2
1
const [blogs, setBlogs] = useState(null)
2
The child component (on which you will update the blogs
state):
JavaScript
1
2
1
<Create blogs={blogs} setBlogs={setBlogs} />
2
On the fetch
‘s then
JavaScript
1
14
14
1
fetch("http://localhost:3001/blogs", {
2
method: "POST",
3
headers: { "Content-Type": "application/json" },
4
body: JSON.stringify(newBlog),
5
}).then((data) => {
6
console.log("newBlog Added");
7
8
setPending(false);
9
setBlogs([blogs, newBlog])
10
11
nav("/");
12
});
13
console.log(newBlog);
14