im fetching data asynchronously then passing it to a client component as props
then sitting the state of the client component and displaying it but it’s not working
the props are passing fine but the state is not getting set for some reason
server component :
export default async function Blog({ params }) {
const id = params.id;
const blog = await GetBlog(id);
return (
<>
<Edit
title="test"
date={blog[0].date_c}
disc={blog[0].disc}
content={blog[0].content}
/>
</>
);
client component :
"use client";
import { useEffect, useState } from "react";
export default function Edit({ _title, _disc, _content, _date }) {
const [title, setTitle] = useState(_title);
const [disc, setDisc] = useState(_disc);
const [content, setContent] = useState(_content);
const [date, setDate] = useState(_date);
return (
<>
<div className="blog-read">
<h2>{title}</h2>
<small>{date}</small>
<p>
<b>{disc}</b>
</p>
<p>{content}</p>
</div>
</>
);
}
It’s supposed to show the components with the data busting from the props
I tried passing a normal string it didn’t work also
the data is being fetched correctly asynchronously
I think the problem might be that the component is being rendered before the data is being fetched but I’m not sure
4
Answers
its the prop name thats my mistake
The issue you are facing is indeed related to the asynchronous nature of fetching data in the server component. The Edit component is receiving the props correctly, but it appears that the props are not being set properly to the state variables. One approach to resolve this issue is to use the useEffect hook in the client component to update the state variables once the props have been received. Here’s how you can modify your Edit component:
By using the useEffect hook with the dependency array [_title, _disc, _content, _date], the state variables will be updated whenever the props change. This ensures that the component will re-render with the updated values from the props. I hope this will resolve your issue.
export default function Edit({ _title, _disc, _content, _date }) {
why are you using underscore in your props ? remove that
The prop’s name is different they should be the same.
Wrong : Edit({ _title, _disc, _content, _date })
Correct : Edit({ title, disc, content, date })
Let me know if it still does not work.