Home > Mobile >  Unable to set posts (posts is a state using useState) after fetching them successfully in useEffect
Unable to set posts (posts is a state using useState) after fetching them successfully in useEffect

Time:01-07

I have successfully fetched posts data from "https://jsonplaceholder.typicode.com/posts" inside useEffect hook that is response is successfully logged to console with data property which contains data (posts) and similarly response.data is also logged to the console with actual posts data but I am unable to set the fetched posts to posts state by setting it using setPosts setter provided by useState hook When I log posts to the console after successfully fetching the posts, my posts state is is empty array [] and also UI doesn't show any posts. I am using React v 18.2.0 can anyone help me about this? Below is my code!

import './App.css';
import { useEffect, useState } from 'react';
import axios from 'axios';

function App() {
const [posts, setPosts] = useState([])

useEffect(() => {
  (async () => {
    const response = await axios.get("https://jsonplaceholder.typicode.com/posts")
    console.log(response)
    const data = response.data
// data contains all the posts which are successfully logged
    console.log(data)

// Here posts is logged as empty array [].........why?
    setPosts(data)
    console.log("posts are", posts)

  })()
  

},[])

 return (
  <div className="App">
    {posts.map(post => {
      <>
        <li key={post.id}> {post.title}</li>
         <p>{post.body}</p>
      </>
    })}
  </div>
  );
}

export default App;


I have successfully fetched posts data from "https://jsonplaceholder.typicode.com/posts" inside useEffect hook that is response is successfully logged to console with data property which contains data (posts) and similarly response.data is also logged to the console with actual posts data but I am unable to set the fetched posts to posts state by setting it using setPosts setter provided by useState hook When I log posts to the console after successfully fetching the posts, my posts state is is empty array [] and also UI doesn't show any posts.

CodePudding user response:

You have missed return part in jsx

import "./App.css";
import { useEffect, useState } from "react";
import axios from "axios";

function App() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    (async () => {
      const response = await axios.get(
        "https://jsonplaceholder.typicode.com/posts"
      );
      console.log(response);
      const data = response.data;
      // data contains all the posts which are successfully logged
      console.log(data);

      // Here posts is logged as empty array [].........why?
      setPosts(data);
      console.log("posts are", posts);
    })();
  }, []);

  return (
    <div className="App">
      {posts.map((post) => {
        return (
          <>
            <li key={post.id}> {post.title}</li>
            <p>{post.body}</p>
          </>
        );
      })}
    </div>
  );
}

export default App;

OR more better

<div className="App">
      {posts.map((post) => (
        <>
          <li key={post.id}> {post.title}</li>
          <p>{post.body}</p>
        </>
      ))}
    </div>

CodePudding user response:

setposts is an asynchronous function, you are printing the values before they are updated. And you should use the return keyword in the arrow function body in curly brace {}, or you should wrap the return value in parenthesis (). The code will look like:

import { useEffect, useState } from "react";
import axios from "axios";

function App() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    (async () => {
      const response = await axios.get(
        "https://jsonplaceholder.typicode.com/posts"
      );
      const data = response.data;
      setPosts(data);
    })();
  }, []);

  return (
    <div className="App">
      {posts.map((post, index) => (
        <>
          <li key={post.id}> {post.title}</li>
          <p >{post.body}</p>
        </>
      ))}
    </div>
  );
}

export default App;

You can check the live demo here: https://codesandbox.io/s/nostalgic-tdd-hwdjxk?file=/src/App.js:0-646

  • Related