Axios Response Data not saved in State - reactjs

I have a custom hook useServerStatus that fetches from a RESTful API with axios. Checking the network tab, the response went through fine, I can see all my data. Using console.log to print out the result or using debugger to check the result in the browser works flawlessly. However, calling the setState method that I get from useState will not save the response data.
ServerStatus Interface (ServerStatus.ts)
interface ServerStatus {
taskid: string
taskmodule: string
taskident?: string
status: string
server: string
customer: string
}
useServerStatus Hook (useServerStatus.ts)
export default function useServerStatus() {
const [serverStatus, setServerStatus] = useState<ServerStatus[][]>([]);
useEffect(() => {
fetchServerStatus();
}, []);
const fetchServerStatus = () => {
axios.get<ServerStatus[][]>(`${config.apiURL}/servers`)
.then(res => setServerStatus(res.data));
}
return serverStatus;
}
Network Tab
https://i.imgur.com/cWBSPVz.png
The first request you see in the network tab is handled the same exact way, no problems there.
React Developer Console
https://i.imgur.com/YCq3CPo.png

Try
const fetchServerStatus = () => {
axios.get<ServerStatus[][]>(`${config.apiURL}/servers`)
.then(res => { setServerStatus(res.data) });
}

So, to answer my own question:
I figured out that the problem wasn't about data not being saved in state, but data not correctly being received by axios.
I fixed it with a workaround. Instead of returning a ServerStatus[][] in my backend, I returned a ServerStatus[]. I was able to use this data instead.

Following the lesson here https://reactjs.org/docs/hooks-custom.html the most obvious thing that jumps out to me is that you aren't returning the state variable serverStatus in your code vs. the example is returning "isOnline". Try to match this by returning serverStatua in your custom effect to see if it helps.

Related

Fetching data with Supabase js and Next.js 13 returns an object (rather than array)

I am trying to fetch data from a Supabase table called "profiles" with Next.js 13 and the app directory. I am trying to take advantage of the new next.js fetching methods, my code looks as follows:
export const revalidate = 0;
export default async function getData() {
const { data: profiles } = await supabase
.from("profiles")
.select("*")
.eq("is_host", true);
console.log(profiles);
return { profiles };
if (!profiles) {
return <p>No hosts found</p>
}
The problem is that this code seems to be wrapping the array returned from Supabase in an object.
The data returned looks like this:
{data:
[
{
"id":"feef56d9-cb61-4c4d-88c6-8a8d7c9493d9",
"updated_at":null,
"username":"username",
"full_name":"Full Name",
"avatar_url":"URL",
"website":null,
"is_host":true,
"bio":null,
"languages":6
}
]
}
When I use useState and useEffect instead, the data is returned as expected, and I can map through it.
Does anybody have an idea why, and how I can prevent that?
Thanks in advance.
I worked it out, through a subsequent error, which I as able to solve thanks to the question I asked here and the helpful hints I got from there.
return { profiles };
Returns the array inside an object.
By removing the {} I was able to fetch the array inside of it.

Update React Component With Updated Data From Firestore

I have a chrome extension that stores data in Firestore and populates that data to the frontend. I always have to refresh the page to see newly added data, which isn’t a user friendly experience. How can I update the UI to show the newly updated data without having to refresh the page?
So far, I've tried using useEffect to get the data. Inside of it, I'm using a function that gets data from Firestore cached inside of chrome local storage.
Here is my code
const getFolderData = () => {
getDataFromChrome("docId").then((res: any) => {
setDocId(res.docId);
});
getDataFromChrome("content").then((res: any) => {
//console.log("getting in mainfolder",res);
// for (const item of res.content) {
// if (item.type.toLowerCase() === "subfolder") {
// // console.log(item)
// getSubFolder(item.id);
// }
// }
for (const item of res.content) {
setTiersContent((pre: any) => [...pre, item]);
}
});
};
useEffect(() => {
getFolderData();
}, []);
I also get this error. I'm also using the chrome extension API to communicate with a background script. It could be related to the problem
Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received
I've never used firebase so I'm not sure what your functions do, I can only guess. A few things wrong from what I can see:
Your useEffect is set to only run on page load since the dep array is empty, I assume you want to refetch on some condition.
If any of the 2 functions is supposed to be a subscription, your useEffect needs to return a cancel function.
Refetch data when needed is not a new problem, packages like React Query has tools that optimize your requests and refetch when needed. I suggest you give it a shot if your app has more than 2-3 fetch requests.

Why does ASP.NET Core 6 MVC Route handler not accept data from axios post request?

I want to post an id to the backend and get the expected result, so
here is the code in the frontend side :
import axios from "axios"
export async function getList(val) {
return await axios.post('http://localhost:5107/PlantsInfo', { id:val }).then(({ data }) => {
return data;
});
}
and in the backend, I have code something like this:
app.MapPost("/PlantsInfo", ([FromServices] DastShafaContext context, int? id) =>
{
// database interaction code according to the id
}
When I attempt this and check it by setting a breakpoint, it takes a request but without an id (that is null)...
But when I attempt to pass an id through Postman, everything is okay.
I think it seems the main problem is related to Axios.
How can I fix it?
This is how my problem was solved!
return await axios.post('http://localhost:5107/GetPlantInfoById?id=' + val).then(({ data }) => {
return data;
});
But this is not the standard way.
I still welcome the best way

React native async storage issues

In my react native app I am trying to save data into my local storage. It works fine most of the time but sometime I get error while setting the item.
So here is the code for me setting the item
async setString(key: string, value: any) {
try {
return await AsyncStorage.setItem(key, value)
} catch (e) {
LogService.logError(
'apiClient',
'apptype',
`Error setting local storage, key: ${key} error: ${JSON.stringify(e)}`,
)
}
}
One of the thing is that my error doesn't prints.
IOS users are having this issues
Do I need to first delete the item and then write to it? Doesn't setString override the value?
Is there any storage problem on the client?
Try using JSON.parse() when getting and JSON.stringify() when setting it
It's worked for me, you can try this.
useEffect(() => {
AsyncStorage.getItem('isLaunched').then((value) => {
AsyncStorage.setItem('isLaunched', 'true'); // No need to wait for `setItem` to finish, although you might want to handle errors
}); // Add some error handling, also you can simply do
}, []);

Invalid character found in method name error when fetching an api using React

I have implemented a table using ag-grid react. I fetch data from an api to fill in that table.
const getDataForTable = async () => {
try {
//apis to fetch the data
setGridData(apiData);
}
catch (err) {
console.error(err);
}
}
useEffect(() => {
getDataForTable();
}, []);
Now, I have also created an onClick method for deleting selected rows of the table. I am removing the rows from api as well. Once the rows are deleted, I just want to refresh the grid with updated data. Currently it only works if I explicitly reload the page.
const onClickRemoveRowsByIds = async () => {
selectedRows.forEach(d => {
listOfIds.push(d.Id);
});
if (window.confirm("Are you sure ?")) {
await listOfIds.map((ele) => removeActiveList(ele));
getDataForTable()
}
}
But when I make a call to getDataForTable function, I get bad request error for the apis. On looking at the reponse body of the api : I get Invalid character found in method name. HTTP method names must be tokens. The authToken and rest of the information remains same but still fetch is not working again. Am I missing some step, or doing it completely wrong? The delete works fine, just the refresh is not happening.

Resources