I’m reading data from an api and storing it in the projekter
variable (useState
). When I map the variable all the values are shown, but when I try to pass the the values to an another component through the link, I get or undefined or can not read properties of undefined ("reading state")
Any suggestions or ideas?
Here I’m getting the data through the getContentData
func and storing it in the projekter
variable
import mistoContentful from "../Helpers/mistoContentful";
const ProjektMain = () => {
const [projekter, setProjekter] = useState([]);
const { getContentData } = mistoContentful();
useEffect(() => {
getContentData().then((response) => setProjekter(response));
}, [getContentData]);
return (
<div className="projektMain">
I then map the variable and everything works so far, but the problem is when I try to pass the data trough the state props to the component SingularProjekt
<div className=" gridContainer grid gap-6 grid-flow-row justify-center mt-60 mb-40 md:grid-cols-3 md:mx-11 xl:mx-16 2xl:mx-auto 2xl:max-w-max 2xl:gap-14 ">
{projekter.map((projektInfo) => (
<div
key={projektInfo.id}
className=" gridItem box-border aspect-square 2xl:max-w-[30rem] relative"
>
<Link
key={projektInfo.id}
to={{
pathname: "/SingularProjekt",
state: { info: projektInfo },
}}
>
<img
className=" object-cover bg-cover h-full hover:border-[#D4B572] hover:border-4"
src={projektInfo.projectCover}
/>
<div className="absolute text-center opacity-90 bottom-0 bg-slate-500 w-[100%] h-[1.5rem] 2xl:h-8">
<p className=" font-oswald opacity-100 2xl:text-xl">
{projektInfo.projectTitle}
{/* {console.log(projektInfo)} */}
</p>
</div>
</Link>
</div>
Component where I want to pass the data trough the state props of the <Link>
comp, I get the error of undefined or cannot read undefined (reading state).
const SingularProjekt = (props) => {
const { projektInfo } = props.location.state;
return (
<div className=" bg-[#666E70] h-full ">
<Nav />
<div className="flex relative md:max-w-[95%] lg:pt-10 2xl:max-w-[100rem] 2xl:mx-auto">
<img className="md:pl-5" src={tapas} />
<div className=" divShadow1 flex items-center justify-center bg-[#505E57] aspect-square absolute bottom-[-11%] right-3 text-center ">
<p className=" font-oswald text-base max-w-[80%] md:text-2xl lg:text-3xl xl:text-4xl 2xl:text-5xl">
Ho`s Tapas{console.log(projektInfo)}
</p>
</div>
2
Answers
try using " ? " :
You are setting key name as "info" while navigating;
When accessing the variable, you should change this
to this: