0

After setting the state reactJs comes up with an error blogs.map is not a function. How do I convert blogs into arrays, although it is initialized as an array.

  const [blogs,setBlogs] = useState([]);
  useEffect(async() => {
        await axios.get(`${API_URL}/api/getblogs`,{
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }
        })
        .then((res)=>{
          res.data.result.forEach(element => {
            element.blogArray.forEach((b)=>{
             // console.log(b);
              setBlogs(b);
            })
          });
          
        })
        .catch((err)=>{
          console.log(err)
         
        })
      }, []);
    

      useEffect(()=>{
          console.log(blogs)
      },[blogs]);

return(
     <div className="row">
              {
                
                blogs &&
                blogs.map((blog)=>{
                  return (
                    
                   <Cardschema key={Math.random()}/>
                  )
                  
                })
                
              }
              </div>
)
1
  • It looks like you just want to do setBlogs(res.data.result). Why are you looping over it? You're overwriting the state with an individual blog every time the forEach iterates. Commented Mar 3, 2021 at 7:41

2 Answers 2

1

You should not call setBlogs method multiple times. Instead aggregate all the data and set it once

.then((res)=>{
     var blogs = []
     res.data.result.forEach(element => {
            element.blogArray.forEach((b)=>{
                 // console.log(b);
                 blogs.push(b);
            });
     });
     setBlogs(blogs);          
});
 
Sign up to request clarification or add additional context in comments.

Comments

1

Since blogArray already is an array you should be able to do:

setBlogs([...blogs, ...blogArray])

and skip at least the second loop.

Now I can imagine you might want to modify the data before setting it to state in that case I would recommend not using forEach like your code but map (at least for the nested loop). Which would look like this.


const formattedBlogrray = element.blogArray.map((blog)=> {
   // do formatting
   return {
      ...formattedBlog,
      
   }
});
setBlogs([...blogs, ...formattedBlogArray])                

1 Comment

Thank you for your response :). This could be one of the solutions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.