0

I am trying to update an array in reducer

let initialState = {
count: 0,
todos: [],
id:0,
 }

const authReducer = (prevState = initialState, action) => {
switch (action.type) {
    case types.ADD_TO_DO:
        console.log(action.todo)
        
        return {
           ...prevState,
            todos: prevState.todos.concat(action.todo)
        }
    default:
        return prevState;
}
}

And I am getting array in the form

todos:['qwerty', 'abcdef']

But I want in the form of

todos:[{id:'1', todo:'qwerty'},{id:'2',todo:'abcdef'}]

How can I achieve this?

Thanks!!!

2 Answers 2

2

In order to convert todos:['qwerty', 'abcdef'] to your expected format, you can map it:

var todos=['qwerty', 'abcdef'];
var result = todos.map((todo, i)=>({id:i+1, todo}));

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

2

You can use reduce for this task

const todos = ['qwerty', 'abcdef']

const data = todos.reduce((acc, rec, index) => {
  return [...acc, {
    id: index + 1,
    todo: rec
  }]
}, [])

console.log(data)

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.