user17048286
user17048286

Reputation:

Why we get error while set the useState method in react?

Here I am using the react usestate hook I have make the usestate as

const { blogs, setBlogs } = useState([{postId:"",blogCity:"",blogTitle:"",username:"",time:""}]);

Now I want to store multiple blogs in this usestate But the useEffect hook return the error of setBlogs is not a function. the code of useEffect is

useEffect(() => {
        fetchProfileImage();
        fetchPost();
        getBlogs();
    }, [postImage,blogs,setBlogs])

I fetched the blogs from getBlogs function where the function is

const getBlogs =async()=>{
    const response = await fetch(
        `http://localhost:5000/api/post/getPost/${username}`, {
        method: "POST",
        headers: {
            'Content-Type': 'application/json',
            'auth-token': localStorage.getItem("token")
        }
    });
    const json = await response.json();
    console.log(json.result);
    setBlogs( json.result);
    console.log("here",blogs);
}

The blog data is fetched properly from the database but it can't be stored by setBlogs. How I can store the blog data in blogs usestate. The error is

User.js:75 Uncaught (in promise) TypeError: setBlogs is not a function
    at getBlog

The error occurs while I use setBlogs usestate.

Upvotes: 0

Views: 626

Answers (1)

user1817574
user1817574

Reputation:

useState returns an array of two elements: an object representing the current state and a setter for the state. You have to deconstruct what useState returns into an array with two objects instead of an object with two properties as you do now.

Wrong: const { blogs, setBlogs } = useState([...]);

Correct: const [ blogs, setBlogs ] = useState([...]);

Upvotes: 3

Related Questions