0
 {moduleCode: ‘xxx, moduleName: ‘xxxx’, subModules: Array(4), features: Array(2)}

when I tried the below code is working

setNewSelectedModules(prev => [
    ...prev,
    { moduleCode: e.target.id, moduleName: e.target.value }
]);

I'm not able to update the inner array But pls guide me on how to update subModules, which is an inner array of objects ->

suModules:[{moduleCode: ‘xxx, moduleName: ‘xxxx’}]
4
  • 1
    What is the previous state? What should the new state look like? Commented Jan 28, 2022 at 10:31
  • Please try this: setNewSelectedModules(prev => ({...prev, subModules: [...prev.subModules, {moduleCode: 'someCode', moduleName: 'someName'}]}));. The assumption is that the useState is like so: const [newSelectedModules, setNewSelectedModules] = useState({});. In other words, newSelectedModules is an object which has the prop subModules. Commented Jan 28, 2022 at 11:07
  • Hi Ramesh, its an empty state and I recreate the array of objects after the user selects modules, submodules, features etc... (the original array is having the entire modules, sub modules etc...) Commented Jan 28, 2022 at 13:26
  • I am getting TypeError: prev.subModules is not iterable, Commented Jan 28, 2022 at 14:10

1 Answer 1

1

You can achieve it using map. Update the "some-condition" as per your scenario.

setNewSelectedModules(prev => ({
    ...prev,
    subModules: prev.subModules.map((item) => {
        if("some-condition"){
            return {
                ...item,
                moduleCode: e.target.id,
                moduleName: e.target.value
            };
        } else {
            return item
        }
        
    })
}));
Sign up to request clarification or add additional context in comments.

5 Comments

@Paul, let me know if this is not clear
thank you Amila, let me try and get back.
I am not able to use the above code since I am creating this array while user gives input for the module, sub module selections.
What does your initial state look like? can you add more relevant code into the question?
const [newSelectedModules, setNewSelectedModules] = useState('');

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.