score:2
Use a separate variable like a simple count mechanism:
const [count, setCount] = useState(0);
<button onClick={() => setCount(count + 1)} />
Then use 'count' as the stateful variable, as well as the url (if the user searched for something different):
useEffect(() => {
const fetchData = async () => {
const result = await axios(url);
setData(result.data);
};
fetchData();
}, [url, count]);
score:0
I think the flow you describe could be simplified if, after making your initial api request, an action is dispatched to fetch the latest data that's available. Subsequently, the request should be made every time the component mounts, that way your component is not responsible for making sure it has the most updated data. This flow would look something like:
1) GET
list
2) enter new item, save
3) make POST
request
4) have an operation (outside of the consuming component) handle the response, and if it's successful, dispatch
an action to refire the initial GET
list call and if not, a call to handle the error.
score:2
Here is a different approach. Maybe there is a better way but in this situation, it seems working.
You can return fetchData
from the useDataApi
and then use it in the onClick
handler and look for the URL change by the help of useRef
. In order to do that you should move fetchData
outside of the useEffect
and wrap it with useCallback
...
const fetchData = useCallback(
async () => {
setIsError(false);
setIsLoading(true);
try {
const result = await axios(url);
setData(result.data);
} catch (error) {
setIsError(true);
}
setIsLoading(false);
},
[url],
);
useEffect(() => {
fetchData();
}, [url, fetchData]); // add fetchData here as a second dependency
return [{ data, isLoading, isError }, setUrl, fetchData]; // add fetchData here as the third returned variable.
};
Then in your App you can use refs to check if the URL is not changed:
function App() {
const [query, setQuery] = useState('redux');
const latestQuery = useRef(query); // define the ref
const [{ data, isLoading, isError }, doFetch, fetchData] = useDataApi(
'https://hn.algolia.com/api/v1/search?query=redux',
{ hits: [] },
);
return (
<Fragment>
<form
onSubmit={event => {
// check the query change
if (latestQuery.current === query) {
fetchData();
}
doFetch(
`https://hn.algolia.com/api/v1/search?query=${query}`,
);
// set current query to the ref value
latestQuery.current = query;
event.preventDefault();
}}
>
.....
I'm not quite sure this is a better solution since I'm still learning the hooks myself, too :)
Source: stackoverflow.com
Related Query
- How to fetch data on page load and then on button click with useEffect
- How to fetch data and then perform other tasks asynchronously on load with useEffect (React JS)
- How to fetch data with multiple requests in Redux action creator and then send collected data to reducer?
- How to fetch data only on first click via react-query and then disable refetch on subsequent clicks
- Trying to fetch axios data with redux, and load it in a component using useEffect
- How to open a page in new tab on click of a button in react? I want to send some data to that page also
- How to dispatch an redux action to load data inside useEffect on page load
- ReactJS - how to fetch multiple data with useEffect
- How can I make my input field prefilled with data and editable on page load?
- how to properly replace axios api with fetch api and map over the received data in nodeJS?
- How to make react data grid table cell editable and focused on click of a button without performing a double click action
- how to delete all data and the update the page without refreshing using useEffect
- react hook useEffect to fetch data on button click (typescript)
- How can I Fetch and display Mysql data into ReactJS front end with Node JS as backend?
- how to set an useEffect to fetch data from API at first render with eslint-react-hooks?
- How to Create a dropdown Button with see more option and on click toggle should not happen in react js?
- How to open a new page with specific dataset with a button click in react?
- How can I fetch data with useEffect in react
- How to pass variable to graphql from method when onClick with button and get it's return data back?
- How to fetch data from a custom React hook (API) with onClick and display it in a Div using TypeScript?
- How can i use useParams() with an onClick button to navigate to different pages and display the data in react.js?
- How to fire a setState function in react from child componenet to parent componenet with data from a button click
- How to use data stored in cache with SWR hooks, and how to make SWR fetch only one time
- How to trigger useEffect() with multiple dependencies only on button click and on nothing else
- How to load and display data with React from an API running on localhost
- How can I show tooltip info for 4 seconds on page load and then hide, then after show on hover?
- How to fetch data and make a route with the same endpoint React
- React Show data with page refresh on Button click
- How to test a component that fetches data in useEffect and stores it in state with react-testing-library and jest?
- how to hide load more button after all data fetch from API?
More Query from same tag
- Unable to interact with firebase real time database emulator
- I get a Nan error certainly due to my render() business logic
- Child component updates parent state unexpectedly in react
- ReactJS JSX Use Shorthand to Perform Multiple Executions
- Conditional asignment with yield
- Django ReactJS: Pass array from JavaScript frontend to Django Python backend
- I need Regex to mask email address in javascript
- Navigate through child routes using react-router-dom V6
- React-Router-Dom v5.2 , unable to pass props to a child component from prop recieved by parent
- Typescript map array of objects giving error: property '(property)' does not exist on type object
- Use componentDidMount variables from event functions
- TS2339: Property X does not exist on type '{}'
- React front-end on AWS EC2?
- ReactJS - Unexpected token '.' error
- How can I place text inside an SVG circle with React JS?
- Calling function using spread operators
- Django response code 200 React accept error code
- active classes for menu items , its should not active all list
- how to align two images using DIV which has row and column spanning image and texts in CSS
- Equivalent in React of *ngFor in Angular 2
- React-three-fiber with react-spring animations
- ReactJS render function isn't being updated
- fill ant design Table with data from state
- How to change modal-dialogue width to 100%
- Unnecessary escape character: \` no-useless-escape
- How to use Webpacker for React on an existing Rails 5.0.2 application?
- Parsing error when trying to add class via state to list item element
- Agora RTC with React issue
- Checking if the first letter of the string is uppercase
- react exclude config files from build