im getting an error that setArrivalId() is not a function, i would like to set the id to arrivalId, can someone plz help:(
now im getting an error that says too many rerenders
import React, { useContext } from "react";
import { IdContext } from "./IdContext";
import { useHistory } from "react-router-dom";
export default function ErrorPage() {
const { arrivalInfo, destinationInfo } = useContext(IdContext);
const { setArrivalId, setDestinationId } = useContext(IdContext);
let arrivalData = Array.from(arrivalInfo);
let destinationData = Array.from(destinationInfo);
const history = useHistory();
let count = 0;
let count2 = 0;
return (
<div>
{arrivalData.map((d) => {
let id = d.PlaceId;
const handleClick = () => {
setArrivalId(id);
count += 1;
if (count2 === 1 && count === 1) {
history.push("/Main");
}
};
return <button onClick={handleClick}>{d.PlaceName}</button>;
})}
{destinationData.map((d) => {
let id = d.PlaceId;
const handleClick2 = () => {
setDestinationId(id);
count2 += 1;
if (count2 === 1 && count === 1) {
history.push("/Main");
}
};
return <button onClick={handleClick2}>{d.PlaceName}</button>;
})}
</div>
);
}
ok i wrote it but the other thing i have an api key i dont want to show. if i dont put the api key it is hard to understand why im getting infinte rerenders and etc
The infinite rerenders is probably because you are calling setId when rendering. So each time it renders, it sets the id, and then has to render again.
If you want to pass the PlaceId to the click handler, remove the setId line, and do something like this:
Then you can change handleClick to take that id as a parameter. The id longer needs to be a hook.
I think the general rule is don’t use state for passing messages.
In general with an event handler, just pass the information about ‘which’ button it is as arguments to the function. Which button is clicked isn’t part of the state of an app. The state part is the arrivialId which you are probably using correctly.