How do I use data that I fetched from DB in useState?

Viewed 787

So I'm using useEffect hook to fetch my data from database and after I get that data I want to set it as useState for title and postBody, but it doesn't work, because useEffect hook runs "last", how can I fix it?

Code:

const [cPost, setCPost] = useState([]);
  const postId = id.match.params.id;

  useEffect(() => {
    axios.get('http://localhost:5000/posts/'+postId)
      .then(posts => {
        setCPost(posts.data);
        console.log("SAS");
      })
  }, []);

   const [title, setTitle] = useState(cPost.title);
   const [postBody, setPostBody] = useState(cPost.postBody);
1 Answers

As a temporary and quick solution, you can use such workaround:

const [cPost, setCPost] = useState();
const [title, setTitle] = useState();
const [postBody, setPostBody] = useState();

const postId = id.match.params.id;

useEffect(() => {
  axios.get('http://localhost:5000/posts/'+postId)
    .then(post => {
      setCPost(post.data);
      console.log("SAS");
    })
}, []);

useEffect(() => {
  if(cPost) {
    setTitle(cPost.title);
    setPostBody(cPost.postBody);
  }
}, [cPost]);

Or the second option:

const [cPost, setCPost] = useState();
const [title, setTitle] = useState();
const [postBody, setPostBody] = useState();

const postId = id.match.params.id;

useEffect(() => {
  axios.get('http://localhost:5000/posts/'+postId)
    .then(post => {
      setCPost(post.data);
      setTitle(post.title);
      setPostBody(post.postBody);
      console.log("SAS");
    })
}, []);

But in the future I would recommend doing side effects like API requests and others using special libraries or create hook for making API requests.

For example redux-saga or redux-thunk.

And use a state manager like redux or mobx.

P.S. and consider whether you need to store the title and body separately in the component state. I have a strong suspicion that you have no need for it.

Related