简体   繁体   中英

How to update Parent component from Child component in React (Functional)

I have the following functional component called RoomManagement. On the first render, fetchRooms gets called, which in turn initially set the state variables with data from a database.

I have a child component called RoomManagementModal, where I pass both my setLoading and fetchRooms function.

I'm having trouble re-rendering the parent component. I click a button in the child component (this adds something to the database). So I'm trying to then get the new data by calling props.fetch() once again but this time from the child, which I thought would trigger a state change on the parent, but it doesn't seem that way.

I can't seem to find a way to kind of force the parent component to render again, if that is possible

function RoomManagement() {

    const [rooms, setRooms] = useState([]);
    const [unavailableRooms, setUnavailableRooms] = useState();
    const [loading, setLoading] = useState(true);

    const fetchRooms = async () => {
        await getAllRooms().then((res) => {
            res.json().then(data => setRooms(data))
        });
        await getAllRoomsUnavailable().then((res) => {
            res.json().then(data => setUnavailableRooms(data[0]))
        })
        setLoading(false)
    }
    
    useEffect(() => {
        fetchRooms();
    }, []);
    
    return (.....
   <RoomManagementModal setLoading={setLoading} fetch={fetchRooms}/>
)

}
export default RoomManagement;
<Button
          onClick={() => {
            if (form.room_id && form.start && form.end) {
              createRoomUnavailable(form).then((res) => {
                if (res.status != 200 && res.status != 201) {
                  res.text().then((e) => setError(e));
                } else {
                  props.fetch()
                }
              });
            } else {
              setError("Missing required Room Id or date time.");
            }
          }}
        >
          Submit
        </Button>

Parent component

1.Declare a state and a setter for the title or slug 2.Define a function to update the state 3.Pass that function down as props to the child component

Child Component

1.Define a function that handles and calls the function passed as props 2.from the parent component

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM