Undefined 404 and React Hook useEffect has a missing dependency - reactjs

I have a super cute site for flower-fans where you can find a profile of a flower (a mock api), read some info and put a note on each and every flower. Though, I'm not able to make the note stick anymore. So frustrating as it worked a while ago. I have updated the dependencies and also the settings for deploying on Netlify. In Postman I get the same message as in the console, which is not found 404.
I get a message in Terminal that the React Hook useEffect has a missing dependency (flowerId) too.
Down below you'll see the error message and here is a link to my deployed site:
https://flowerinspoapi.netlify.app/
Error message from Console
GET https://flowerinspoapi.netlify.app/flowers/undefined 404
Code from Flowerinfo.js
// Fetching the comments for the flowers
const url = "https://flowers-mock-data.firebaseio.com/comments/TheresaUlwahn"
export const FlowerInfo = () => {
const { flowerId } = useParams()
const [flower, setFlower] = useState([])
const [flowerMessages, setFlowerMessages] = useState([])
const [postedMessage, setPostedMessage] = useState("")
// Fetching the ID of the flowers
useEffect(() => {
fetch(`https://flowers-mock-data.firebaseio.com/flowers/${flowerId}.json`)
.then((res) => res.json())
.then((json) => {
setFlower(json)
})
}, [flowerId])
// Fetching the messages
useEffect(() => {
fetch(`https://flowers-mock-data.firebaseio.com/comments/TheresaUlwahn/${flowerId}.json`)
.then((res) => res.json())
.then((json) => {
console.log('All messages for the flower: ', json)
if (json !== null) {
setFlowerMessages(json)
}
})
}, [postedMessage])
const handleFormSubmit = (flowerId, message) => {
// console.log('POST THIS MESSAGE: ', message, 'FOR THE FLOWER: ', flowerId);
fetch(url + `/${flowerId}/.json`, {
method: "POST",
body: JSON.stringify({ message }),
headers: { "Content-Type": "application/json" }
})
.then(() => {
console.log('posted !')
// window.location.reload();
setPostedMessage(message)
})
.catch(err => console.log("error:", err))
}
var result = Object.keys(flowerMessages).map(function (key) {
return [key, flowerMessages[key]];
});

Related

I'm successfully fetching the RapidAPI pnr data, but unable to display it on the react page, attached API schema

I'm succesfully fetching the data from API but unable to display it on the page. I tried like this
<ListGroupItem>
Charting : {data.properties?.chart_status}
</ListGroupItem>
but not getting it on page.
const fetchData = async () => {
if (context.pnr === '') {
return alert("Enter your PNR!")
} else {
await Axios.get(url, {
headers: {
'X-RapidAPI-Key': 'c7f77319b7mshbf31f81334ba8c6p172803jsn8c0911e4683a',
'X-RapidAPI-Host': 'pnr-status-indian-railway.p.rapidapi.com'
}
})
.then(res => {
setData(res.data)
console.log("Response: ", res.data)
})
.catch(err => console.log(err))
}
setData('')
}
Attached is data base schema

useEffect: How to put data in the state in order

I'd like to ask how to retrieve data through use Effect.
The flow I want is as follows.
First, I want to get the 'cards' state, fill the cards with data, and then fill the data through the cardsPromises after that.
But my code couldn't get cards and wordAll, and the empty value came out.
I think it's because the cards are still empty, but I don't know how to operate in order.
Please tell me how to do it.
const [wordAll, setWordAll] = useState([]);
const [cards, setCards] = useState([]);
useEffect(() => {
axios
.get("http/api/words/", {
headers: {
Authorization: cookies.token,
},
})
.then((response) => {
setCards(response.data);
})
.catch((error) => {
console.log(error);
});
const cardsPromises = cards.map((contents) =>
axios.get(
`http/api/words/detail_list/?contents=${contents.contents}`,
{
headers: {
Authorization: cookies.token,
},
}
)
);
console.log("cards", cards);
Promise.all(cardsPromises)
.then((response) => {
console.log("resp", response.data);
setWordAll(response.data);
})
.catch((error) => {
console.log("err==>", error);
});
}, []);
You are correct, cards array is still empty in the useEffect callback when the fetching the data. I suggest converting to async/await and waiting for the first fetch to resolve and using that value of cards for the fetching of the rest of the data.
const [wordAll, setWordAll] = useState([]);
const [cards, setCards] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const{ data: cards } = await axios.get(
"http/api/words/",
{
headers: {
Authorization: cookies.token,
},
},
);
setCards(cards);
const cardsPromises = cards.map((contents) =>
axios.get(
`http/api/words/detail_list/?contents=${contents.contents}`,
{
headers: {
Authorization: cookies.token,
},
}
);
);
const wordAllResponse = await Promise.all(cardsPromises);
const wordAll = wordAllResponse.map(({ data }) => data);
setWordAll(wordAll);
} catch (error) {
// handle any errors, rejected Promises, etc..
}
};
fetchData();
}, []);
Wrap your 2nd axios call inside a function, and call it after 1st axios call returns.
useEffect(() => {
const getWords = (cards) => {
const cardsPromises = cards.map((contents) =>
axios.get(
`http/api/words/detail_list/?contents=${contents.contents}`,
{
headers: {Authorization: cookies.token}
}
)
);
Promise.all(cardsPromises)
.then((response) => {
setWordAll(response.data);
})
.catch((error) => {
console.log("err==>", error);
});
})
axios
.get("http/api/words/", {
headers: { Authorization: cookies.token },
})
.then((response) => {
const cards = response.data;
setCards(cards);
getWords(cards);
})
.catch((error) => {
console.log(error);
});
}, [])
Now dependency chain is clearer.

change api fetch into axios call

i am trying to change the api fetch into axios get method i dont know how to do that
const fetchApi = () => {
const request = getAllActivityData();
request
.api({
params: {
customer,
},
})
i want to call api like this using axios
i have added full code in codesandbox it will be helpfull if u can edit the codesand box and make it working
useEffect(() => {
const config = {
headers: {
Authorization: `token
},
};
axios.get("customer/get-all-activity-data/?customer=22", config)
.then((res) => {
console.log(res.data);
});
code sandbox
https://codesandbox.io/s/upbeat-jasper-2jmri?file=/src/App.js:3137-3298
what i have tryed the data is not showning but there are no error .
i am getting data in postman
https://codesandbox.io/s/gifted-montalcini-j7nv7?file=/src/App.js
Do you mean something like this, using async await...
const axiosCallFn = async () => {
let url = '...'
let config = {
headers: {
token: '...'
}
}
try {
let resp = await axios.get(url, config)
return resp.data
} catch(e) {
throw e
}
}
// import the function into your component and use it like so
axiosCallFn()
.then((data) => {
// your functionality here.
})
.catch(() => {
// your error functionality here.
})
and then you can call your axiosCallFn in your useEffect.

Updating useEffect api call url with user inputs

I'm working on a project, where I need to update a datachart with user inputted dates. I'm having trouble on how to update the url inside the useEffect hook. Here's my relevant code:
const finalUrl =`${apiUrl}id=${id}&timing=${time}&start=${finalStart}&end=${finalEnd}`;
console.log(finalUrl);
useEffect(() => {
axios
.get<AxiosResponse>(finalUrl, {
headers: {
"Content-Type": "application/json"
}
})
.then(response => {
setData(response);
})
.catch(error => {
console.log(error);
});
}, []);
console.log(data);
Everything looks good until i get to the axios call. I cannot get useEffect to use the updated url. Logging the response data just gives the same every time. All values inside "finalUrl" are coming from the user.
I'm going to assume that apiUrl and id never change, but that all the other things you're using in the API URL are inputs from the user.
If so, you need to rebuild the URL in the useEffect callback, and make the callback dependent on those user inputs, like this:
useEffect(() => {
const finalUrl =`${apiUrl}id=${id}&timing=${time}&start=${finalStart}&end=${finalEnd}`;
axios
.get<AxiosResponse>(finalUrl, {
headers: {
"Content-Type": "application/json"
}
})
.then(response => {
setData(response);
})
.catch(error => {
console.log(error);
});
}, [time, finalStart, finalEnd]);
The callback will be called again when time, finalStart, or finalEnd change.
Note that you also need to disregard or cancel previous requests when the dependencies change, even if the request hasn't been completed yet. I don't use axios but as I understand it has a "cancel/cancellation token" you can use for doing that. Here's what it would look like with fetch, which uses AbortController:
useEffect(() => {
const finalUrl =`${apiUrl}id=${id}&timing=${time}&start=${finalStart}&end=${finalEnd}`;
// Create the controller so we can cancel the request
const controller = new AbortControlller();
// Pass `signal` to fetch vvvvvvvvvvvvvvvvvvvvvvvvvvv
fetch<DataType>(finalUrl, {signal: controller.signal})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
return response.json();
})
.then(setData)
.catch(error => {
console.log(error);
});
// Return a cleanup callback
return () => {
// Cancel the request since its response would be out of date
controller.abrt();
};
}, [time, finalStart, finalEnd]);
console.log(data);

React Native axios api call Shopify

Good morning guys, I try to fetch data from Shopify using this method. But it does not working.
Request failed with status code 400
May you share your little experience ?
I'm working on React Native Project.
const api_key = "example-api-key";
const password = "example-password";
const version = "2021-07";
const url = `https://${api_key}:${password}#store-example.myshopify.com/admin/api/${version}/products.json`;
useEffect(() => {
axios({
method:'get',
url:url
}).then((result) => {
console.log(result.data)
}).catch(error => {
console.log(error)
})
});
It's most likely that the authentication is failing. Move the auth parameters to axios header. Try this
const username = "example-api-key";
const password = "example-password";
const version = "2021-07";
const url = `https://store-example.myshopify.com/admin/api/${version}/products.json`;
useEffect(() => {
axios({
method:'get',
url,
auth: { username,password }
}).then((result) => {
console.log(result.data)
}).catch(error => {
console.log(error)
})
});

Resources