@
@
@Predaytor2020-04-13 13:42:00
React
@Predaytor, 2020-04-13 13:42:00

React. How to pass updated state on change in child component?

const getAllLists = () => {
  const data = [
    {
      id: 1,
      title: "The Vines",
      wrapped: false
    },
    {
      id: 2,
      title: "AURORA",
      wrapped: false
    },
  ];
  return data;
};


The parent that should render when the state is updated in the setWrapped method.

import React, { useState, useEffect } from "react";
import { getAllLists } from '../api';

import { List } from "./List";

export const Lists = () => {
  const [lists, setLists] = useState([]);

  useEffect(() => {
    const fetchLists = async () => {
      const data = await getAllLists();
      setLists(data);
    };

    fetchLists();
  }, []);
  

  const setWrapped = id => {
    const data = lists;
    const idx = data.findIndex(i => i.id === id);
    data[idx].wrapped = !data[idx].wrapped;
    console.log(data[idx]);
    setLists(data);
  };

  return (
    <>
       {lists.map(list => (
         <List key={list.id} list={list} setWrapped={setWrapped}>{...}</List>
       ))}
    </>
  );
}


List component with parent props:

import React from "react";

export const List = ({ list, children, setWrapped }) => {
  const { id, title, wrapped } = list;

  return (
    <div className="list">
      <div className="list-top">
        <h1>{title}</h1>
        <button onClick={() => setWrapped(id)}>Click</button>
      </div>

      {!wrapped && (
        <div className="cards">
          {children}
        </div>
      )}
    </div>
  );
}


But the List component does not rerender, although the data in the general Lists changes. Why? How to update the general state correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-04-13
_

const data = lists;
it's the same memory location, try data = [...lists] to make a copy

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question