1

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?

tukitooo1998
  • 337
  • 10
  • I will advice you to read about "data down action up" principle. Let the parent component handle the fetching and creating of the article, and after a successful article creation add it to the existing articles. https://medium.com/swlh/understanding-information-flow-in-react-data-down-action-up-b6c792a8b010 – Joshua Opata Jul 14 '23 at 22:37
  • You can use the `useRouter` hook for quickly solution: https://nextjs.org/docs/app/api-reference/functions/use-router#userouter, OR add props to each component to trigger data fetching. – Emre Jul 14 '23 at 22:40
  • i am trying to use useRouter but i am not being able to render the new post, can you see my now edited question? @Emre – tukitooo1998 Jul 15 '23 at 00:15
  • It's because that's fake "resource will not be really updated on the server". @tukitooo1998 – Emre Jul 15 '23 at 11:33
  • Does this answer your question? [Why can't I "PUT" data on JSONPlaceholder through Postman?](https://stackoverflow.com/questions/46290632/why-cant-i-put-data-on-jsonplaceholder-through-postman) – Emre Jul 15 '23 at 11:34

0 Answers0