I am creating a post app with NextJS, i am using the jsonplaceholder
API, axios, and the app directory.
I have rendered my list of posts as follows in ListOfPosts.jsx
'use client'
import { useEffect, useState } from "react";
import Link from "next/link";
import axios from "axios";
export default function ListOfPosts() {
const [posts, setPosts] = useState([]);
useEffect(() => {
const fetchPosts = async () => {
try {
const response = await axios.get(
'https://jsonplaceholder.typicode.com/posts'
);
setPosts(response.data);
} catch (error) {
console.log(error);
}
};
fetchPosts();
}, []);
return posts.map(post => (
<Link href={'/posts/[id]'} as={`posts/${post.id}`} key={post.id}>
<article key={post.id}>
<h2 style={{color: '#09f'}}>{post.id} {post.title}</h2>
<p>{post.body}</p>
</article>
</Link>
))
}
And this is how i am creating a new post
'use client'
import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import axios from 'axios';
async function addPost(title, body, userId) {
try {
const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
title,
body,
userId,
});
console.log('New post created:', response.data);
// Handle success or any other logic here
} catch (error) {
console.error('Error creating post:', error);
// Handle error or any other logic here
}
}
function NewPost() {
const router = useRouter();
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const [userId, setUserId] = useState(1);
const handleSubmit = async (e) => {
e.preventDefault();
await addPost(title, body, userId);
router.push('/posts');
// Reset form inputs
setTitle('');
setBody('');
};
return (
<div>
<h2>Create New Post</h2>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="title">Title:</label>
<input
name="title"
type="text"
id="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
required
className='text-red-500'
/>
</div>
<div>
<label htmlFor="body">Body:</label>
<input
type="text"
id="body"
value={body}
onChange={(e) => setBody(e.target.value)}
required
className='text-red-500'
/>
</div>
<button type="submit">Create Post</button>
</form>
</div>
);
}
export default NewPost;
Both components are being rendered in the posts/page.jsx:
import ListOfPosts from "./ListOfPosts";
import NewPost from "./NewPost";
export default function PostsPage() {
return (
<>
<section>
<NewPost/>
<ListOfPosts />
</section>
</>
);
}
But for some reason after i create a post it is not being displayed in the list of posts. How should i update my ListOfPosts component to render the new post?