Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
How to replace an state without mutating?

I am using React and Redux and i need to update my state with updated data. My state contains an array of objects like this:

[
    {
        "messages": [/*somedata*/],
        "users": [/*somedata*/],
        "avatar": "/*somedata*/",
        "_id": "/*somedata*/",
        "type": "/*somedata*/",
        "createdAt": "/*somedata*/",
        "__v": 0
    },
    {
        "messages": [/*somedata*/],
        "users": [/*somedata*/],
        "avatar": "/*somedata*/",
        "_id": "/*somedata*/",
        "type": "/*somedata*/",
        "createdAt": "/*somedata*/",
        "__v": 0
    }
]

So in this reducer, i just want to replace or update the entire state array with my payload but without mutate my state. My payload also contains the same array of objects as above but with updated data.

const chatsReducer = (state = chats, {type, payload}) => {
  switch (type) {
    case '@updateChats':
        return state = payload //i need something like this but without mutating
    default:
        return state
  }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This should help you, it creates a new array and populates it with all the objects within your payload array.

const chatsReducer = (state=chats, {type, payload}) => {
  switch (type) {
    case '@updateChats':
        return [ ...payload ];

    default:
        return [ ...state ];
  }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!