"Error: Rendering Issue with React Child Object"

17 views Asked by At

This error occurs in a React application when attempting to render an object directly as a child component. React expects children to be valid React elements, but it encountered an object instead, likely containing keys such as id, firstName, lastName, email, bio, and profilePic:

function UpdateProfilePage() {
    const [user, setUser] = useRecoilState(userAtom);
    const storedData = JSON.parse(localStorage.getItem("CurrentUser"));
    const [inputs, setInputs] = useState({
        name: storedData.firstName,
        lastName: storedData.lastName,
        email: storedData.email,
        bio: storedData.bio,
        password: "",
        profilePic: storedData.profilePic,
    });
    const fileRef = useRef(null);
    const [updating, setUpdating] = useState(false);
    const showToast = useShowToast();
    const { handleImageChange, imgUrl } = usePreviewImg();

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (updating) return;
        setUpdating(true);
        try {
            const userId = storedData?.id; // Use optional chaining to avoid errors if storedData is undefined
            if (!userId) {
                throw new Error("User ID is undefined");
            }
            const res = await fetch(`${BASE_URL}/update/${userId}`, {
                method: "PUT",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({ ...inputs, profilePic: imgUrl }),
                credentials: "include", // Include credentials with the request
            });
            const data = await res.json(); // updated user object
            if (res.ok) {
                showToast("Success", "Profile updated successfully", "success");
                setUser(data.user);
                localStorage.setItem("CurrentUser", JSON.stringify(data.user));
            } else {
                showToast(
                    "Error",
                    data.error || "An error occurred while updating the profile",
                    "error"
                );
            }
        } catch (error) {
            console.error("Fetch error:", error);
            showToast("Error", error.message, "error");
        } finally {
            setUpdating(false);
        }
    };

    return (
        <form onSubmit={handleSubmit}>
            <Flex align={"center"} justify={"center"} my={6}>
                <Stack
                    spacing={4}
                    w={"full"}
                    maxW={"md"}
                    bg={useColorModeValue("white", "gray.dark")}
                    rounded={"xl"}
                    boxShadow={"lg"}
                    p={6}
                >
                    <Heading lineHeight={1.1} fontSize={{ base: "2xl", sm: "3xl" }}>
                        User Profile Edit
                    </Heading>
                    <FormControl id="userName">
                        <Stack direction={["column", "row"]} spacing={6}>
                            <Center>
                                <Avatar
                                    size="xl"
                                    boxShadow={"md"}
                                    src={imgUrl || storedData.profilePic}
                                />
                            </Center>
                            <Center w="full">
                                <Button w="full" onClick={() => fileRef.current.click()}>
                                    Change Avatar
                                </Button>
                                <Input type="file" hidden ref={fileRef} onChange={handleImageChange} />
                            </Center>
                        </Stack>
                    </FormControl>
                    <FormControl>
                        <FormLabel>Full name</FormLabel>
                        <Input
                            placeholder="John Doe"
                            value={inputs.name}
                            onChange={(e) => setInputs({ ...inputs, name: e.target.value })}
                            _placeholder={{ color: "gray.500" }}
                            type="text"
                        />
                    </FormControl>
                    <FormControl>
                        <FormLabel>User name</FormLabel>
                        <Input
                            placeholder="johndoe"
                            value={inputs.lastName}
                            onChange={(e) => setInputs({ ...inputs, lastName: e.target.value })}
                            _placeholder={{ color: "gray.500" }}
                            type="text"
                        />
                    </FormControl>
                    <FormControl>
                        <FormLabel>Email address</FormLabel>
                        <Input
                            placeholder="[email protected]"
                            value={inputs.email}
                            onChange={(e) => setInputs({ ...inputs, email: e.target.value })}
                            _placeholder={{ color: "gray.500" }}
                            type="email"
                        />
                    </FormControl>
                    <FormControl>
                        <FormLabel>Bio</FormLabel>
                        <Input
                            placeholder="Your bio."
                            value={inputs.bio}
                            onChange={(e) => setInputs({ ...inputs, bio: e.target.value })}
                            _placeholder={{ color: "gray.500" }}
                            type="text"
                        />
                    </FormControl>
                    <FormControl>
                        <FormLabel>Password</FormLabel>
                        <Input
                            placeholder="password"
                            value={inputs.password}
                            onChange={(e) => setInputs({ ...inputs, password: e.target.value })}
                            _placeholder={{ color: "gray.500" }}
                            type="password"
                            autoComplete="current-password"
                        />
                    </FormControl>
                    <Stack spacing={6} direction={["column", "row"]}>
                        <Button bg={"red.400"} color={"white"} w="full" _hover={{ bg: "red.500" }}>
                            Cancel
                        </Button>
                        <Button
                            bg={"green.400"}
                            color={"white"}
                            w="full"
                            _hover={{ bg: "green.500" }}
                            type="submit"
                            isLoading={updating}
                        >
                            Submit
                        </Button>
                    </Stack>
                </Stack>
            </Flex>
        </form>
    );
}

export default UpdateProfilePage;

enter image description here

0

There are 0 answers