Getting user data with req.body inside a useEffect that then displaying inside a table
I got a problem when I try the normal fetch method inside my react app not returning anything and think something to do with my req.body. I have tried using axios.get but giving me varouis errors.
See below my code: useEffect with fetch: (Don't return anything)
React.useEffect(()=>{
const manager = {
"manager":managerName
}
fetch(`http://localhost:5000/staff/getStaffM`,manager)
.then(resp=>resp.json())
.then(data=>setData(data))
},[]);
useEffect with axios.get: (returning the following error = Unhandled Promise Rejection: TypeError: resp.json is not a function. (In 'resp.json()', 'resp.json' is undefined) )
React.useEffect(()=>{
const manager = {
"manager":managerName
}
axios.get(`http://localhost:5000/staff/getStaffM`,manager)
.then(resp=>resp.json())
.then(data=>setData(data))
},[]);
Backend Routing:
const getStaffM = asyncHandler(async(req,resp)=>{
const staff = await Staff.find({employeeManager: req.body.manager})
if(staff){
resp.status(200).json(staff)
}
else{
resp.status(400)
throw new Error ("Could not find this manager")
}
This is working when I try it in post man but not in React app.
See below successful postman screenshot:
do you know?
how many words do you know
See also questions close to this topic
-
how to change prettier format for react native
my code formatting prettier didn't works well for react native, i don't understand where to config it but it works well with flutter
from this code
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( <View> <Text>Apps</Text> </View> ) }
it's formatted to this
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( < View > < Text > Apps < /Text> < /View> ) }
-
react-router-dom v6 params only numbers
I want add number regex in may param in react-router-dom v6. it work fin in v5 like it:
<Route path="list/:id(\d+)" element={<MyComponent/>} />
but it not work in v6.
-
How can I fixed my problem"FirebaseError: Firebase: Error (auth/invalid-api-key)."
My environment variable is ok. No comas and name mistakes but they given me error like "FirebaseError: Firebase: Error (auth/invalid-api-key)". How can I fixed it. Please Help me...
This my .env file
REACT_APP_apiKey=AIzaSyBWobnhbdeMdNpXXXXXXXXXXXXXXXXXXXX REACT_APP_authDomain=XXXXX.firebaseapp.com REACT_APP_projectId=XXXX REACT_APP_storageBucket=XXXXX.appspot.com REACT_APP_messagingSenderId=4997390XXXXX REACT_APP_appId=1:4997390XXXXX:web:cc7bc80aa1bdb78fXXXXXX REACT_APP_measurementId=G-M1XDXXXXXX
This my firebase config file
const firebaseConfig = { apiKey: process.env.REACT_APP_apiKey, authDomain: process.env.REACT_APP_authDomain, projectId: process.env.REACT_APP_projectId, storageBucket: process.env.REACT_APP_storageBucket, messagingSenderId: process.env.REACT_APP_messagingSenderId, appId: process.env.REACT_APP_appId, measurementId: process.env.REACT_APP_measurementId, }; when I debugging firebaseConfig object console.log(firebaseConfig.apiKey); ==========> undefined console.log(firebaseConfig.authDomain); ==========> undefined console.log(firebaseConfig.projectId); ==========> undefined console.log(firebaseConfig.storageBucket); ==========> undefined console.log(firebaseConfig.measurementId); ==========> undefined console.log(firebaseConfig.appId); ==========> undefined console.log(firebaseConfig.measurementId); ==========> undefined
client side given error this "FirebaseError: Firebase: Error (auth/invalid-api-key)"
-
Async function passed as prop into React component causing @typescript-eslint/no-misused-promises error
I have the following asynchronous submitNewPatient function which is throwing @typescript-eslint/no-misused-promises error message from elint. Is it possible to adjust the function such that it removes this error?
const submitNewPatient = async (values: PatientFormValues) => { try { const { data: newPatient } = await axios.post<Patient>( `${apiBaseUrl}/patients`, values ); dispatch({ type: "ADD_PATIENT", payload: newPatient }); closeModal(); } catch (e: unknown) { if (axios.isAxiosError(e)) { console.error(e?.response?.data || "Unrecognized axios error"); setError( String(e?.response?.data?.error) || "Unrecognized axios error" ); } else { console.error("Unknown error", e); setError("Unknown error"); } } };
Component used to pass function as a prop:
<AddPatientModal modalOpen={modalOpen} onSubmit={submitNewPatient} error={error} onClose={closeModal} />
I have also tried the following which removes the eslint error message based. However, seems like I am not entering the async code block (perhaps not triggering the async() function):
const submitNewPatient = (values: PatientFormValues) => { async () => { try { const { data: newPatient } = await axios.post<Patient>( `${apiBaseUrl}/patients`, values ); dispatch({ type: "ADD_PATIENT", payload: newPatient }); closeModal(); } catch (e: unknown) { if (axios.isAxiosError(e)) { console.error(e?.response?.data || "Unrecognized axios error"); setError( String(e?.response?.data?.error) || "Unrecognized axios error" ); } else { console.error("Unknown error", e); setError("Unknown error"); } } }; };
-
NextJS: Error serializing `.data.data` returned from `getServerSideProps`
I'm new to NextJS. I'm working on a simple page in which I need to retrieve data from my backend app. My backend app is a totally separate app written in go. My undestanding is that I must use
getServerSideProps
to get data from the server on load, so I've got the following:myProject/pages/category/new.js
:export default function AddNewCategory(data) { ... } export const getServerSideProps = async () => { const data = await getAllCategories(); console.log(await data) return { props: { data: { data } } }; };
myProject/api/category.js
:import axios from "axios"; // getAllCategories returns a list of all active categories export const getAllCategories = async() => { axios.get("http://127.0.0.1:8080/api/v1/categories") .then(function (response) { console.log(response.data) return response.data; }) .catch(error => { console.error("error") console.log(error) }) }
As you can see I've got a print statement in
getAllCategories
which prints:{ data: [ { id: 1, name: 'Pop', slug: 'pop', description: 'Pop', parent: 0, active: true, created_at: '2022-05-03T19:50:00-04:00', updated_at: '2022-05-03T19:50:00-04:00', deleted_at: null }, { id: 3, name: 'Pop 2', slug: 'pop-2', description: 'Pop', parent: 0, active: true, created_at: '2022-05-03T19:50:24-04:00', updated_at: '2022-05-03T19:50:24-04:00', deleted_at: null } ] }
yet I'm getting the following error:
error - Error: Error serializing
.data.data
returned fromgetServerSideProps
in "/category/new". Reason:undefined
cannot be serialized as JSON. Please usenull
or omit this value.I saw around that I should try to convert the data to string and then back to json:
return { props: { data: JSON.parse(JSON.stringify(data)) } };
but when I do this I'm getting a different error:
error - SyntaxError: Unexpected token u in JSON at position 0
I'm using
next@12.1.5
Any idea what's going on?
-
Is there any way to avoid preflight OPTION request?
I'm creating a react app using the Laravel API and sending requests through Axios but a preflight OPTION request is sent with every GET or POST request
although these preflight requests are not causing me any trouble, I just want to get them out of the way.
I've done enough reading on CORS to know that only simple requests don't need preflight requests, and since my requests contain authorization headers, they are not considered simple.
I've tried:- adding a proxy field to my package.json
- creating a middleware for preflight requests
There was no success with any of the above.
As far as I can tell, this is the only answer that will work, Why is an OPTIONS request sent and can I disable it?, But I have no idea where to add this header: Access-Control-Allow-Origin: *
Or I can add this: Access-Control-Max-Age: 600 , Yet again, I'm not sure where it belongs. I mean, I am not sending the option request, so how am I supposed to set headers for something I am not even sending?
Okay, enough with the explaining, here is my post request:
axios.post(`/ticket/create`, formData).then(res => { if (res.status === 201) { alert('success') } else { alert('request failed') } })
Here are my axios configs:
axios.defaults.baseURL = 'http://127.0.0.1:8000/api'; axios.interceptors.request.use(function (config) { const token = localStorage.getItem('auth_token'); config.headers.Authorization = token ? `Bearer ${token}` : ''; return config; })
- adding a proxy field to my package.json
-
Can someone help me understand how async + await + useEffect work in React?
I have a React app built with the Minimal template and I'm trying to follow along with one of their tutorials, in order to create a Redux slice that feeds some data to a custom component. The data itself is collected from Firebase. Below is my code:
firebase.js - helper
export function getDocuments(col) { const colRef = collection(db, col); const q = query(colRef, where('uid', '==', auth.currentUser.uid)); getDocs(q).then((snap) => { const data = snap.docs.map((d) => ({ id: d.id, ...d.data() })); return data; }); // return [1,2,3] }
product.js - Redux slice
export function getProducts() { return async (dispatch) => { dispatch(slice.actions.startLoading()); try { const products = await getDocuments('products'); dispatch(slice.actions.getProductsSuccess(products)); } catch (error) { dispatch(slice.actions.hasError(error)); } }; }
ProductList.js - component
const dispatch = useDispatch(); const { products } = useSelector((state) => state.client); useEffect(() => { dispatch(getProducts()); }, [dispatch]); useEffect(() => { if (products.length) { // setTableData(products); } }, [products]);
If I console log
data
in the helper function (firebase.js), I get the values I expect, once the promise is resolved/fulfilled. However, if I console.logclients
in the product.js slice or later in the component, I getundefined
. I assume my problem is not being able to understand how async + await + useEffect work together in order to fix this. My assumption is that I am trying to access the value before the promise is resolved and therefore before the helper function returns it. I confirmed that by returning a simple array[1, 2, 3]
in my helper function as a test.I think I am missing something fundamental here (I am not very experienced with React and JS in general and still learning things on the go). Can someone help me understand what am I doing wrong?
Thank you!
-
UseEffect firing on initial render
I am creating a front end for an API that requires a user to input both an API key as well as a device name. The issue is that the UseEffect() fetch is firing with 'undefined' as the API key on render, so the API is throwing a 401 Error code and preventing the page from rendering so that the user can put in a key.
See below code:
Api.js
const Api = ({ device, key }) => { const [data, setData] = useState(null); useEffect(() => { fetch(`APILINK&key=${key}&id=${device}`) .then((res) => res.json()) .then(setData) }, [device, key]) if (data) return ( <> <tbody> <tr> <th>Date</th> <th>Temp</th> <th>C02</th> </tr> {data.samples.map((item) => ( <tr> <td>{item.time}</td> <td>{item.data[0]}</td> <td>{item.data[1]}</td> </tr> ))} </tbody> </> ) return <div>No Data Found</div> }
Home.js
const Home = ({ setDevice, setKey }) => { const getData = (e) => { e.preventDefault(); const newDevice = e.target.deviceID.value; const apiKey = e.target.apiKey.value; setDevice(newDevice); setKey(apiKey); } return ( <> <h1>Type in a device and provide an API key below:</h1> <form onSubmit={getData}> <input type='text' placeholder="Enter Device..." id='deviceID'></input> <input style={{display: 'block'}} type='text' placeholder="Enter API Key..." id='apiKey'></input> <button>Search</button> </form> </> ) } export default Home;
App.js
const App = () => { const [device, setDevice] = useState() const [key, setKey] = useState() return ( <> <Home setDevice={setDevice} setKey={setKey} /> <Api device={device} key={key} /> </> ) } export default App;
Any help is appreciated!!
-
How to fix loading spinner when using useEffect Hooks with dependency list?
I am facing one problem when trying to add a spinner. My problem is when I add "product" dependency in useEffect hooks then my loading spinner always spinning and data not showing. Here is my code :
const [product, setProduct] = useState([]); const [msg, setMsg] = useState(''); const [loading, setLoading] = useState(false); const navigate = useNavigate(); // show all products on the manage inventory page useEffect(() => { setLoading(true); (async () => { const data = await fetchAllProduct(); if (data) { setProduct(data); setLoading(false); } })(); }, [product]);
Bellow the return code >>
{ loading === false ? <ProductTable viewProductHandle={viewProductHandle} deleteProductHandle={deleteProductHandle} product={product}> </ProductTable> : <Spinner></Spinner> }
So how do I fix that? pls, help me...