1

I am passing props from a child nested inside a class component

class Viewer extends React.Component {
....
render(){
return(
.....
<DragAndDrop characters={characters}/>
)
}

to the parent functional component

function DragAndDrop(props) {
  console.log("char",props.characters); # I am able to console.log this
  const [characters, updateCharacters] = useState(props.characters); # but doing this throws an error 

  function handleOnDragEnd(result) {
    if (!result.destination) return;

    const items = Array.from(characters);
    const [reorderedItem] = items.splice(result.source.index, 1);
    items.splice(result.destination.index, 0, reorderedItem);

    updateCharacters(items);
  }

  return (
    <div className="App">
      <header className="App-header">
        <h1>Final Space Characters</h1>
        <DragDropContext onDragEnd={handleOnDragEnd}>
          <Droppable droppableId="characters">
            {(provided) => (
              <ul
                className="characters"
                {...provided.droppableProps}
                ref={provided.innerRef}
              >
                {characters.map(({ id, name, thumb }, index) => {
                  return (
                    <Draggable key={id} draggableId={id} index={index}>
                      {(provided) => (
                        <li
                          ref={provided.innerRef}
                          {...provided.draggableProps}
                          {...provided.dragHandleProps}
                        >
                          <div className="characters-thumb">
                            <img src={thumb} alt={`${name} Thumb`} />
                          </div>
                          <p>{name}</p>
                        </li>
                      )}
                    </Draggable>
                  );
                })}
                {provided.placeholder}
              </ul>
            )}
          </Droppable>
        </DragDropContext>
      </header>
    </div>
  );
}

export default DragAndDrop;

but when I pass props.characters to useState, it throw an error, How I can resolve this? thanks

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak. cancel all subscriptions an
Yusuf
  • 2,295
  • 7
  • 15
  • 34

1 Answers1

-1

This problem take place because you initialize state before mount component. If you want to correct your component you can use useEffect inside your component and inside that updateCharacters like below

useEffect(()=>{
      updateCharacters(props.characters);
}, [])

Dependency array is required if you don't want the component rerendering infinitely

user18821127
  • 318
  • 1
  • 8
sajadab
  • 383
  • 2
  • 11