Reputation: 187
I'm new to react/hooks I'm having a bit of trouble getting my head around updating a search on an API based on a user input. I currently have an API that im hitting to get a table of stocks. I then draw this table. I have created some radio buttons that allow the user to click so that it can refine the search on the API. I am passing the value of the selected radio button back to the URL as industrySelection
, what I am hoping for is that the table will update from this result but it doesn't do anything. Could someone please explain how to fix this and why?
function StockTable() {
const [industrySelection, setIndustry] = useState("");
const [rowData, setRowData] = useState([]);
const columns = [
{ headerName: "Stock", field: "name"},
{ headerName: "Symbol", field: "symbol"},
{ headerName: "Industry ", field: "industry"}
];
useEffect(() => {
fetch(`http:PRIVATE/stocks/symbols/${industrySelection}`)
.then(res => res.json())
.then(data =>
data.map(stocks => {
return {
name: stocks.name,
symbol: stocks.symbol,
industry: stocks.industry,
};
})
)
.then(stocks => setRowData(stocks));
}, []);
return (
/* Place Search Options and grab users choice */
<div className = "userSelect">
{
industryChoices.map(feature => (
<ul className = "radioULlist">
<li className = "radioList">
<input type="radio" name="radioButton" value = {feature}
onChange={event => {
const { value } = event.target;
setIndustry(value);
}}
/>
<label className = "radioLabel">{feature}</label>
</li>
</ul>
))}
</div>
/* DRAW TABLE HERE */
);
}
Upvotes: 2
Views: 1727
Reputation: 203155
A hook with empty dependency array is synonymous to componentDidMount
, it runs only once when the component mounts. A hook with a populated dependency array is more like componentDidUpdate
, when a value in the array updates (shallow comparison) the hook's callback is invoked.
Add industrySelection
to the effect's dependency array. When the value of industrySelection
changes the effect will trigger and ultimately update rowData
.
useEffect(() => {
fetch(`http:PRIVATE/stocks/symbols/${industrySelection}`)
.then(res => res.json())
.then(data =>
data.map(stocks => {
return {
name: stocks.name,
symbol: stocks.symbol,
industry: stocks.industry,
};
})
)
.then(stocks => setRowData(stocks));
}, [industrySelection]);
Upvotes: 1
Reputation: 3274
Change the last line of your useEffect from:
}, []);
to
}, [industrySelection]);
So that useEffect will be called everytime your change industrySelection
Upvotes: 1