Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

add in object in array after submit

I am facing a problem. If you can give me some advice, it would be a huge help for me.
i have a state with object

const [work , setWork] = useState({company:"" , jobTitle:"", jobType:"", location:""});

const [list, setList] = useState([]);

I want when the user update and submit the state, I send the object in an array list [ ]

companyValue is is the result of onChange

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const add = (e) => {
            e.preventDefault();
    
            if(companyValue){
                setWork(prevState => ({
                    ...prevState,
                    company: companyValue
                }))
                 setList(prevState => ({
                    ...prevState,
                    work
                 }))
                    }
               }

and i whant to have a result like this

list = [
        {company:"" , jobTitle:"", jobType:"", location:""},
        {company:"" , jobTitle:"", jobType:"", location:""},
        {company:"" , jobTitle:"", jobType:"", location:""}
        ]

>Solution :

Do something like this:

const newWork = {
  ...work,
  company: companyValue
}

setWork(newWork);

setList(
  list.concat(newWork)
)

If you want to add only that companyValue, which I assume look like this: {company:"" , jobTitle:"", jobType:"", location:""}, then you can do this:

setList(
  list.concat(companyValue)
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading