Home > database >  Why component in react dont re-rendering
Why component in react dont re-rendering

Time:12-05

Hello why component in react was not rendering? State was updated and i see it in developer tools but content was not changing

FULL CODE: https://pastebin.com/bxNUAieV

import React, {useState} from 'react'

const List = (props:any) => {
    const [actToDo, changeActTodo] = useState(props.actToDo)
    const [ToDoLists, changeActToDoLists] = useState(props.ToDoLists)
    return (
        <>
            {ToDoLists[actToDo].list.map((e:any, index:any) => (
            <div className={'Todo__element'}>
                <li key={index}>{e}</li><i className="fas fa-check"></i><i className="fas fa-recycle" onClick={() => props.removeElement(index)}></i>
            </div>))}
        </>
    )
}

export default List

ToDoLists[number].list save the list actToDo save number

const removeElement = (index:any) => {
    console.log(index);
    let FullList = ToDoLists
    //@ts-ignore
    FullList[actToDo].list.splice(index,1)
    changeToDoLists(FullList)
    console.log(ToDoLists);
}

CodePudding user response:

you are mutating the array, that will not work, also the console.log will display the wrong value as setState is async.

https://dev.to/il3ven/common-error-accidentally-mutating-state-in-react-4ndg

const removeElement = (index:any) => {
    console.log(index);
    let FullList = { 
       ...ToDoLists,
       [actToDo]: {
          ...ToDoLists[actToDo],
          list: ToDoLists[actToDo].list.splice(index,1)
       }
    }
    console.log(FullList);
    changeToDoLists(FullList);
}

by the way, saving props to state is a bad behavior, as if the prop change nothing will happen.

CodePudding user response:

What I can see in your code is that you are directly modifying a state variable, which we should never do in React. To modify a state variable first make its copy in a new variable, and after making changes , pass that new variable in setState function :

So instead of :

let FullList = ToDoLists

do like this :

let FullList = _.cloneDeep(objects);  //(using Lodash deep clone method here)
changeToDoLists(FullList);

Also , if you want to console your new list, then you should use useContext hook, since useState acts asynchronously and will not update value immediately, so console on very next line will not give updated value :

useEffect(() => {
  console.log('Here is my new list after updation', ToDoLists);
  }, [ToDoLists]);
  • Related