I have App component where the list of items is shown, and ModalForm where you can add a new one. But when I’m adding new item I have to reload the page to see it in my list. I want to trigger somehow my GET method after I execute my POST method.
**App.js**
const App = () => {
let books = useAxiosGet(API_URL)
//some code
return (
//some code
<ModalForm />
);
}
**ModalForm.js**
const ModalForm = () = > {
//some logic for opening modal form
function submit(e) {
e.preventDefault();
axios.post(API_URL, {
name: data.name,
description: data.description,
count: data.count,
imageURL: data.imageURL,
price: data.price
})
.then(res => {
// document.location.reload();
// here I want to trigger GET
console.log(res.data);
})
.catch((err) => {
console.log(err);
})
setData({
name: "",
description: "",
count: "",
imageURL: "",
price: ""
})
}
function handle(e){
const newData={...data}
newData[e.target.id] = e.target.value
setData(newData)
console.log(newData)
}
return (//some code);
}
>Solution :
You should use React State to store your books.
https://ar.reactjs.org/docs/state-and-lifecycle.html
- Make a state for books
const App = () => {
// Books storage.
const [books, setBooks] = useState([]);
}
- Make a function that loads the books.
const App = () => {
// Books storage.
const [books, setBooks] = useState([]);
// Load books
const loadBooks = () => {
const response = useAxiosGet(API_URL);
setBooks(response );
}
}
- Loads the books when component mound using
useEffecthook.
https://ar.reactjs.org/docs/hooks-effect.html
const App = () => {
// Books storage.
const [books, setBooks] = useState([]);
// Load books
const loadBooks = () => {
const response = useAxiosGet(API_URL);
setBooks(response );
}
// Load books when component mount.
useEffect(loadBooks, [])
}
- In your submit function, after the submission success, you can just call
loadBooksagain.
const submit = () => {
...
.then(() => {
loadBooks();
})
}