I am trying to make an API call in useEffect() and want useEffect() to be called everytime a new data is added in the backend. I made a custom Button(AddUserButton.js) which adds a new user in backend. I am importing this button in the file (ManageUsers.js) where I am trying to display all the users. I just wanted to make an useState to keep track everytime an add button is clicked and make useEffect refresh according to it. For Example:
JavaScript
x
16
16
1
const [counter, setCounter] = useState(0);
2
3
const handleAdd = () => {
4
setCounter(state => (state+1));
5
};
6
7
useEffect(() => {
8
// fetch data here
9
10
}, [counter]);
11
12
return(
13
<Button onClick = {handleAdd}> Add User </Button>
14
15
);
16
But currently because I have two .js files, I am not sure how to make my logic stated above work in this case
ManageUsers.js
JavaScript
1
33
33
1
import AddUserButton from "./AddUserButton";
2
3
export default function ManageShades() {
4
5
useEffect(() => {
6
axios
7
.get("/api/v1/users")
8
.then(function (response) {
9
// After a successful add, store the returned devices
10
setUsers(response.data);
11
setGetUserFailed(false);
12
})
13
.catch(function (error) {
14
// After a failed add
15
console.log(error);
16
setGetUserFailed(true);
17
});
18
console.log("Load User useeffect call")
19
20
},[]);
21
return (
22
<div>
23
24
<Grid item xs={1}>
25
26
<AddUserButton title = "Add User" />
27
28
</Grid>
29
30
</div>
31
);
32
}
33
AddUserButton.js
JavaScript
1
13
13
1
export default function AddDeviceButton() {
2
3
4
return (
5
<div>
6
<Button variant="contained" onClick={handleClickOpen}>
7
Add a device
8
</Button>
9
10
</div>
11
);
12
}
13
Advertisement
Answer
A common approach is to pass a callback function to your button component that updates the state of the parent component.
JavaScript
1
27
27
1
import { useState, useEffect } from "react";
2
3
const AddUserButton = ({ onClick }) => {
4
return <button onClick={onClick} />;
5
};
6
7
export default function Test() {
8
const [updateCount, setUpdateCount] = useState(false);
9
const [count, setCount] = useState(0);
10
11
useEffect(() => {
12
setCount(count++);
13
}, [updateCount]);
14
15
return (
16
<div>
17
<AddUserButton
18
onClick={() => {
19
// do something, e.g. send data to your API
20
// finally, trigger update
21
setUpdateCount(!updateCount);
22
}}
23
/>
24
</div>
25
);
26
}
27