Data is not updating with React Hook useEffect() - javascript

I have a little web application that uses axios to fetch some orders from the API. My problem is the new orders only appear when the page is refreshed, they do not update automatically.
Here is my useEffect hook:
useEffect(() => {
setLoading(true);
apiClient
.getEvents()
.then((res) => {
console.log(res);
setOrders(res.data);
setLoading(false);
})
.catch((err) => {
console.log(err);
});
}, []);
And here is where I use axios:
import axios from "axios";
const username = "user";
const password = "pass";
const token = Buffer.from(`${username}:${password}`, "utf8").toString("base64");
const apiClient = axios.create({
baseURL: "API URL",
withCredentials: false,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Basic ${token}`,
},
});
export default {
getEvents() {
return apiClient.get("/orders");
},
getEvent(order_id) {
return apiClient.get("/orders/" + order_id);
},
};

Your problem ist the useEffect-Hook itself.
useEffect(() => {
setLoading(true);
apiClient
.getEvents()
.then((res) => {
console.log(res);
setOrders(res.data);
setLoading(false);
})
.catch((err) => {
console.log(err);
});
}, []);
You pass an empty array as the second argument here: }, []);. When you pass an empty array as second argument to useEffect, it will only run on first mount and then never again.
You can pass different variables in this parameter. In this case, useEffect will run, when of these variables change their value. So, for example, you could have a "Refresh" button which changes a state called refresh which you then pass as a second argument to useEffect.
const [refresh, setRefresh] = useState(false);
useEffect(() => {
if(!refresh) return;
setLoading(true);
apiClient
.getEvents()
.then((res) => {
console.log(res);
setOrders(res.data);
setLoading(false);
setRefresh(false);
})
.catch((err) => {
console.log(err);
});
}, [refresh]);
Just a simple example, it could be done better, of course.
Also, one hint: You can omit the second parameter, the dependency array, of useEffect, which would make it run on every update of your component. Don't do this. In most cases, you will end up in an infinite loop because most of the time you will update the state and cause the component to rerender within useEffect - in your case, using setLoading() would be enough.

Related

React Prop returning Null as it relies on state

Hopefully a simply one.
I make an API call in my component which brings down some account information such as AccountUid, Category etc, i use state to set these.
useEffect(() => {
fetch(feed_url, {
headers: {
//Headers for avoiding CORS Error and Auth Token in a secure payload
"Access-Control-Allow-Origin": "*",
Authorization: process.env.REACT_APP_AUTH_TOKEN,
},
})
//Return JSON if the Response is recieved
.then((response) => {
if (response.ok) {
return response.json();
}
throw response;
})
//Set the Account Name state to the JSON data recieved
.then((accountDetails) => {
setAccountDetails(accountDetails);
console.log(accountDetails.accounts[0].accountUid);
console.log(accountDetails.accounts[0].defaultCategory);
})
//Log and Error Message if there is an issue in the Request
.catch((error) => {
console.error("Error fetching Transaction data: ", error);
});
}, [feed_url]);
This Works perfectly well and it Logs the correct values in my .then when testing it.
The issue however is that i want to pass these down as props. But i get an error that they are being returned as null (My default state).. i presume as they're jumping ahead.
<div className="App">
<GetAccountName
accountUID={accountDetails.accounts[0].accountUID}
defCategory={accountDetails.accounts[0].defaultCategory}
/>
</div>
How do i pass the the 2 details im logging as props?? I've tried setting default state to "" instead of null and just get that it is undefined.
If you dont want to use conditional render in your child component, so you should try optional chaining
<GetAccountName
accountUID={accountDetails?.accounts?.[0]?.accountUID}
defCategory={accountDetails?.accounts?.[0]?.defaultCategory}
/>
Since fetching is asyncronous, the most common way is to show some loading indicator (like a spinner) & once the data come in, show the component instead.
If you don't need an indicator, you might just return null.
The general idea is to manipulate some intermediary states (e.g. data, isError) based on the promise state.
Check out react-query library example or a lighter abstraction like useFetch hook to see how they manage it.
Here's a sample implementation of useFetch taken from this article:
const useFetch = (url, options) => {
const [response, setResponse] = React.useState(null);
const [error, setError] = React.useState(null);
const [abort, setAbort] = React.useState(() => {});
React.useEffect(() => {
const fetchData = async () => {
try {
const abortController = new AbortController();
const signal = abortController.signal;
setAbort(abortController.abort);
const res = await fetch(url, {...options, signal});
const json = await res.json();
setResponse(json);
} catch (error) {
setError(error);
}
};
fetchData();
return () => {
abort();
}
}, []);
return { response, error, abort };
};

react component constantly fetching and updating data for no reason

I have a react component that I'm fetching data with to visualize.
The data fetching is happening constantly, instead of just once as is needed. I was wondering if there is a way to reduce this happening.
The component is like this,
export default function Analytics() {
const {
sentimentData,
expressionsData,
overall,
handleChange,
startDate,
endDate,
sentimentStatistical,
} = useAnalytics();
return (
I'm wondering if I should be using something like componentDidMount() here with componentDidUpdate() ?
UseAnalytics is another component specifically for fetching data, basically just a series of fetches.
There are different buttons to click on the site that can change the data requested, so I do want to be able to change the state of these data objects / request more, i.e., I filter the data based on dates. But confused how to stop it just constantly requesting data.
Thanks in advance,
Update to share the function being called.
export default function useAnalytics() {
let d = new Date();
d.setMonth(d.getMonth() - 1);
const [dateRange, setDateRange] = useState([d.getTime(), Date.now()]);
const [startDate, endDate] = dateRange;
const { data: sentimentData } = useSWR(
`dashboard/sentiment/get-sentiment-timefilter?startTime=${startDate}&endTime=${endDate}`,
fetchSentiment
);
const { data: expressionsData } = useSWR(
`dashboard/expression/get-expression-analytics?startTime=${startDate}&endTime=${endDate}`,
apiRequest
);
return {
sentimentData,
expressionsData,
overall,
handleChange,
setDateRange,
sentimentStatistical,
startDate,
endDate,
};
}
The apirequest is like this,
export async function apiRequest(path, method = "GET", data) {
const accessToken = firebase.auth().currentUser
? await firebase.auth().currentUser.getIdToken()
: undefined;
//this is a workaround due to the backend responses not being built for this util.
if (path == "dashboard/get-settings") {
return fetch(`/api/${path}`, {
method,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: data ? JSON.stringify(data) : undefined,
})
.then((response) => response.json())
.then((response) => {
if (response.error === "error") {
throw new CustomError(response.code, response.messages);
} else {
return response;
}
});
}
return fetch(`/api/${path}`, {
method,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: data ? JSON.stringify(data) : undefined,
})
.then((response) => response.json())
.then((response) => {
if (response.status === "error") {
// Automatically signout user if accessToken is no longer valid
if (response.code === "auth/invalid-user-token") {
firebase.auth().signOut();
}
throw new CustomError(response.code, response.message);
} else {
return response.data;
}
});
}
With the answers,
useEffect(()=>{
// this callback function gets called when there is some change in the
// state variable (present in the dependency array)
},[state variable])
This seems about right, I'm wondering how to substantiate the constants outside of useAnalytics?
In the functional component we don't have componentDidMount() or componentDidUpdate () but we have the workaround for the same by using the useEffect react hook.
For implementing the functionality of componentDidMount() we can utilize the following code snippet
useEffect(()=>{
// this is the callback function that needs to be called only once (when the component has mounted)
},[])
And for implementing the functionality of componentDidUpdate() we can utilize the following code snippet
useEffect(()=>{
// this callback function gets called when there is some change in the
// state variable (present in the dependency array)
},[state variable])
First of all, You are using function component, here you cannot use ComponentDidMount() or ComponentDidUpdate() as they only work in class Components. You will have to use useEffect() but you haven't provided any additional code to understand the situation here.
Anyway if you are setting some state on button click when you fetch data and it is occurring again and again it's probably because you haven't used second argument on useEffect() which states that this useEffect() will only run when the second argument changes.
So to answer your question, pass second argument to useEffect() that you are setting when you click a button.
useEffect(() => {
//
}, [state])
As per your code it's functional component and you can't use componentDidMount() and componentDidUpdate() method as this functions are used in class component.
If you want prevent constantly updating component then there are different ways for both class and functional component.
For Class Component: Only executes if old and new data doesn't match. this function does comparison between old and new value.
componentDidUpdate(prevProps, prevState) { if (prevState.data !== this.state.data) { // Now fetch the new data here. } }
For Functional Component: This is only execute when previous state change.
useEffect(() => { // your data }, [stateName])

Why is the account address from metamask coming back as undefined after storing it in useState()

I have this piece of code that is connecting to metamask wallet and sets the account address using useState().
const [currentAccount, setCurrentAccount] = useState("")
const connectWallet = async () => {
try {
if (!ethereum) return alert("Please install MetaMask.")
const accounts = await ethereum.request({ method: "eth_requestAccounts" })
setCurrentAccount(accounts[0])
console.log(accounts)
// TODO:Add conditional statement to check if user has token
navigate("/portfolio")
} catch (error) {
console.log(error)
throw new Error("No ethereum object")
}
}
console.log("current account", currentAccount)
const returnCollection = async (currentAccount) => {
const options = { method: 'GET', headers: { Accept: 'application/json' } };
fetch(`https://api.opensea.io/api/v1/collections?asset_owner=${currentAccount}&offset=0&limit=300`, options)
.then(response => response.json())
.then(response => console.log("collection owned by current address", response))
.catch(err => console.error(err));
useEffect(() => {
returnCollection(currentAccount)
})
The console is logging the account but when I try to pass it in the returnCollection call in useEffect() it comes back as undefined.
It seems here, you are doing something like this:
useEffect(() => {
returnCollection(currentAccount)
})
This will run after every rerender or every state change, and also initially when the component is first mounted, when currentAccount is "". Initially, current account is "", so you may not want to get the collection from "". Instead, maybe what you can do is create another state variable for the result of the returnConnection, and set the state variable to the result of the returnConnection, since you typically don't return results from useEffect, unless it's a cleanup function. Also, maybe you can check the state of currentAccount inside of the useEffect to make sure it's not "", before returning the result.

Is there a way to put react hooks in a function that's not function component?

I'm trying to create a function that is not a component nor hooks that's callable on speficic event. Let's say i have a simple function that post a data using axios and i want to use navigate after the post is successfull. Here's the example
export const authLogin = (email, password) => {
const config = {
withCredentials: true,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': Cookies.get('csrftoken')
}
}
let navigate = useNavigate();
return dispatch => {
console.log('Masuk ke dalam auth file');
dispatch(authStart());
axios.post('/log_in/', {
email: email,
password: password
}, config)
.then(res => {
if (res.data.error) {
alert(res.data.error)
dispatch(authFail(res.data.error))
}
else {
const token = res.data.key;
const expirationDate = new Date(new Date().getTime() + 3600 * 1000);
localStorage.setItem('token', token);
localStorage.setItem('expirationDate', expirationDate);
dispatch(authSuccess(token));
dispatch(checkAuthTimeout(3600));
alert('login berhasil')
navigate("/", { replace: true });
}
})
.catch(err => {
alert(err);
dispatch(authFail(err))
})
}
}
I have an error that says
but when i try to change the function name with an uppercase letter, another problem occured, how do i resolve this problem?
A hook must be attached to a fiber which is directly attached to the React component tree. You CANNOT use hooks outside the component tree because React can't keep track of them (this is why hooks must always be run in the same order, and can't be conditional, because React keeps track of their state internally).
The only time you can use a hook outside of a component, is from another hook.
In short, you must be able to draw a straight line back from the hook call to React rendering the component tree. If you cannot, then it's an invalid hook call.
THE SOLUTION
...in your case - is to simply pass in the navigate function to your action as a parameter:
const MyComponent = () => {
const navigate = useNavigate();
const doSomethingHandler = () => {
dispatch(authLogin(email,password,navigate))
}
}
const authLogin = (email,password,navigate) => {
// ...do your action and call the `navigate` parameter
// when you need to
}

How to re-render component after fetch request and state change?

I'm new to react and tying in the back end but after I make the fetch requests, I have to reload the page to see any changes. The database is updated as soon as the functions are called but the component doesn't re-render. I know setState works asynchronously, so I tried calling my functions in the callback of setState but that did not work.
This happens on both my handleSubmit and handleDelete functions. My initial get request is in my componentDidMount so I'm including that in case it helps.
I couldn't find the answer that I needed on the site, maybe the recommendations were just off but here I am, lol. Thanks in advance.
componentDidMount() {
// todos is the data we get back
// setting the state to newly aquired data
fetch("/api/todos")`enter code here`
.then(res => res.json())
.then(todos => this.setState({ todos }, () =>
console.log("Todos fetched...", todos)))
.catch(err => console.log(err))
}
// onClick for submit button
handleSubmit = (e) => {
e.preventDefault();
const data = this.state;
fetch("/api/todos", {
method: "post",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
};
// onClick for delete button
handleDelete = (e) => {
e.preventDefault();
let uniqueId = e.target.getAttribute("id")
fetch(`/api/todos/${uniqueId}`, {
method: "delete",
headers: { 'Content-Type': 'application/json' }
})
};
// Some of the JSX if needed
<DeleteBtn
id={todo._id}
onClick={this.handleDelete}
>X</DeleteBtn>
<Form onSubmit={this.handleSubmit} id="myForm"></Form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
The result I'm looking for is once I add a todo, for it to render on my list immediately, rather than only upon page reload.
Return the details from the back-end in the requests, use that values to update the state,
Currently you just perform the operation on the back-end and front-end doesn't know that it happened in the back-end.
The Best way is to either pass the full data(list or object) back to front-end after operation performed on the DB and link the values to a state,
if the data is bulk then send a success message(200 is enough) back from back-end to front-end and if success change the value(list) in front-end,
Link the value(list) to a state in front-end to have a re rendering of the component.
you've to update your state, and once you'll update the state your component will re-render and it'll shows the latest changes.
Here i am assuming "todos" you've set in your state is an array, then just update it on deleting and adding.
i.e:
// onClick for submit button
handleSubmit = (e) => {
e.preventDefault();
const data = this.state;
const currentTodos = [...this.state.todos]
fetch("/api/todos", {
method: "post",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
}).then(()=>{
currentTodos.push(data);
this.setState({todos:currentTodos})
})
};
// similarly for delete you can do
// onClick for delete button
handleDelete = (e) => {
e.preventDefault();
let uniqueId = e.target.getAttribute("id")
let currentTodos = [...this.state.todos];
fetch(`/api/todos/${uniqueId}`, {
method: "delete",
headers: { 'Content-Type': 'application/json' }
}).then(()=>{
let updatedTodos = currentTodos.filter(todo=>todo._id !==uniqueId);
this.setState({todos:updatedTodos})
})
};
You are probably not changing your state "todos" that is why it doesn't render. You could fetch todos after every change (after remove, update, add...) or change the state yourself.
Methode 1:
componentDidMount() {
this.getTodos();
}
getTodos = () => {
//fetch todos, setState
}
handleSubmit = () => {
fetch(...).then(this.getTodos);
}
handleDelete = () => {
fetch(...).then(this.getTodos);
}
Methode 2:
componentDidMount() {
this.getTodos();
}
getTodos = () => {
//fetch todos, setState
}
handleSubmit = () => {
fetch(...);
let todos = this.state.todos;
todos.push(newTodo);
this.setState({todos});
}
handleDelete = () => {
fetch(...);
let todos = this.state.todos;
//remove todo from todos
this.setState({todos});
}

Categories

Resources