I want to make a list of user details by filling the form with name, email, designation, phone & image input field, I've saved the form data in an object and sent the form data to it's parent using props addedUser(userData);
, I'm using this addedUser
prop in the parent component to send the data to the firebase and then use the same fetched data to make a list of users in array.
I've made loadedData
empty array simply wanna push the data into it but the responseData.json()
doesn't give me anything, the data is being saved to firebase perfectly but I'm facing problems using it.
Please check the code here and also the <Users />
component code where I'm trying to make the list:
Parent:-
function App() {
const [userData, setUserData] = useState([]);
const fetchData = useCallback(async () => {
try {
const responseData = await fetch(
"https://react-users-db-default-rtdb.asia-southeast1.firebasedatabase.app/users.json"
);
const data = responseData.json();
console.log(data);
const loadedData = [];
for (const key in data) {
loadedData.push({
key: key,
userName: data[key].userName,
userEmail: data[key].userEmail,
userDesignation: data[key].userDesignation,
usePhone: data[key].usePhone,
userImage: data[key].userImage,
});
}
console.log(loadedData);
setUserData(loadedData);
} catch (err) {
console.log(err);
}
}, []);
useEffect(() => {
fetchData();
}, [fetchData]);
async function recieveUserData(users) {
const responseData = await fetch(
"https://react-users-db-default-rtdb.asia-southeast1.firebasedatabase.app/users.json",
{
method: "POST",
body: JSON.stringify(users),
headers: {
"Content-Type": "application/json",
},
}
);
const data = await responseData.json();
console.log(data);
}
return (
<main>
<div className="form__wrap">
<AddUserForm addedUser={recieveUserData} />
</div>
<div className="user__wrap">
{userData.length > 0 ? (
<Users newUser={userData} />
) : (
<p>No user found</p>
)}
</div>
</main>
);
}
Users Component:
export default function Users({ newUser }) {
console.log(newUser);
return (
<div className="usercard__wrap">
{newUser.map((el, i) => {
return (
<UserCard
key={i}
name={el.userName}
email={el.userEmail}
designation={el.userDesignation}
phone={el.userPhone}
image={el.userImage}
/>
);
})}
</div>
);
}
Data is going to firebase:-
But responseData.json()
is giving me this, I can't see my user object to access:-
CodePudding user response:
In your fetchData function you need to await responseData.json().
const data = await responseData.json();