简体   繁体   中英

I can't access the elements of an array via bracket notation in the frontend but it works in the backend

I am new to coding and I am experiencing a really strange problem. There is an array coming from a database in the backend and I want to access the single elements of the array in the frontend via bracket notation. I can access the single elements of the array in the backend. But in the frontend, I receive an error message when I try to access the elements.

Here is my GitHub repo for the project: https://github.com/LittleWing85/Homepage_For_A_Friend And you can see the website here: https://website-for-portfolio.herokuapp.com/

In /client/src/modules/Project.js, I am retreiving an object with data from the backend and storing the object in a variable called project :

export default function Project() {
    const dispatch = useDispatch();
    const projectId = useSelector((state) => state.portfolio.projectId);
    const [project, setProject] = useState({});

    useEffect(() => {
        fetch("/api/project/" + projectId)
            .then((response) => response.json())
            .then((data) => {
                setProject(data);
            });
    }, [projectId]);

The object has a property with the key gallery_pictures and its value is an array. With this code I was trying to display the first element of that array:

return (
        <div className="content">
            ...
            <p>{project.gallery_pictures[0]}</p>

In the console of my browser I receive the error message project.gallery_pictures is undefined :

screenshot of error message

But if I change the code <p>{project.gallery_pictures[0]}</p> to <p>{project.gallery_pictures}</p> , the content of the array is displayed:

screenshot of displayed content from array

For this reason I don't understand why the console says that project.gallery_pictures is undefined.

I tried to access the elements of this array in the backend console in /server/server.js with the same approach in this code and it worked fine:

const express = require("express");
...
app.get("/api/project/:id", (request, response) => {
getProjectDataById(request.params.id).then((result) => {
response.json(result);
console.log(Array.isArray(result.gallery_pictures));
console.log(result.gallery_pictures[0]);
>     });
> });

screenshot of working code in backend

What is it that I am not getting? Why can't I access the elements of the array in the frontend?

Within the useEffect you fetch data from your sever and, as soon as you receive a response, set project to the received data. However, while waiting for the server response project is still the initial value {} , thus project.gallery_pictures is still undefined.

As a solution, you could add a condition that checks if project is still undefined, and if yes instead render a loading screen.

This is happening because the request hasn't completed by the time that your component attempts to render itself. Inside your component adding a condition will do the trick

{project?.gallery_pictures !== undefined && Array.isArray(project.gallery_pictures) ? project.gallery_pictures[0] : null}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM