Home > Blockchain >  add in object in array after submit
add in object in array after submit

Time:09-05

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

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:""}
        ]

CodePudding user response:

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)
);
  • Related