I have component structure like this
src
--App
--DataTableComponent
--ButtonComponnet
axios
--useAxios
On app load I am calling Axios
library in DataTableComponent
(through custom hook useAxios
) to fetch some data, then later when user clicks a button in ButtonComponent
I would like Axios
to load data again in DataTableComponent
, but I am not sure how as the components are siblings.
CodePudding user response:
You can just send some prop var or function that will return true or something when button is clicked. Do you call ButtonComponnent in DataTableComponent or somewhere else ?
CodePudding user response:
What you're trying to do is get two sibling components to communicate and call functions from each other, if I'm understanding correctly. If they're siblings, I'd recommend using a third-party library like Redux or EventHub
If you have Component A with the function "updateData", then you can call it in Component B using Redux by setting up a reducer called "updateData", and having DataTableComponent subscribe to the "data"
Redux file:
import { createStore, combineReducers } from "redux";
const reducer = (state = {}, action) => {
... {axios fetch here}
};
const store = createStore(reducer);
export default store;
DataTableComponent.jsx:
import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import axios from "axios";
import { updateData } from "../redux/actions";
const DataTableComponent = () => {
const data = useSelector(state => state.data);
const dispatch = useDispatch();
const fetchData = () => dispatch(updateData());
return (
<div>
<button onClick={fetchData}>Fetch Data</button>
<table>{data.map((item, index) => <tr key={index}><td>{item.id}</td><td>{item.name}</td></tr>)}</table>
</div>
);
};
ButtonComponent.jsx:
import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import axios from "axios";
import { updateData } from "../redux/actions";
const ButtonComponent = () => {
const data = useSelector(state => state.data);
const dispatch = useDispatch();
const fetchData = () => dispatch(updateData());
return (
<div>
<button onClick={fetchData}>Fetch Data</button>
<table>{data.map((item, index) => <tr key={index}><td>{item.id}</td><td>{item.name}</td></tr>)}</table>
</div>
);
};