0

I am working on a simple blog website as my first Web Dev project. In the page where I write a blog, I am using a simple svg icon with an onClick listener to add a paragraph to the blog. This works like Medium where when you click on the "+" icon, it adds a new paragraph for you to write. Here is the code of my onClick event listener function:

function addNewPara() {
        // let newContent = {
        //     date: blogContent.date,
        //     author: blogContent.author,
        //     title: blogContent.author,
        //     contentArray: blogContent.contentArray.push("")
        // };
        // setBlogContent(newContent);

        setBlogContent(prevValue => {
            prevValue.contentArray.push("")
            return {
                ...prevValue,
            }
        });
    }

This has two ways where I update the state value. The issue here is that when I click the plus icon and this method is triggered, it pushes two empty strings into the contentArray key.

If I uncomment and switch to the other method, I get the following error: TypeError: blogContent.contentArray.map is not a function

The TypeError occurs where I am using the array to render the relevant HTML elements. What could be the issues behind this?

3
  • You have not provided enough code to analyse, I can only assume that setBlogContent is some sort of state update, but then why would you modify previous state (prevValue)? Commented Jul 13, 2021 at 10:36
  • Did you try to console.log(Array.isArray(blogContent.contentArray)) and console.log(blogContent.contentArray)? I think the problem might be that what you expect to be an array actually is not an array Commented Jul 13, 2021 at 10:38
  • @Lukasz'Severiaan'Grela the Udemy course suggested that way wherein we can use the prevValue. Also, reading your comment makes me realize the stupid mistake I was making. I was modifying the previous value and then adding more to that array. Hence it added two new values instead of one. Thanks Commented Jul 13, 2021 at 11:44

1 Answer 1

1

this should be your setable method

setBlogContent({...blogContent, contentArray: [...blogContent.contentArray, "your new item"]})
Sign up to request clarification or add additional context in comments.

Comments

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.