What is the reason why map is not reading the array when I refresh the webistr

The data comes from my server.

The code when I work on it, but after I refresh it, it say map does not read the values.

import {Link} from 'react-router-dom';
import axios from 'axios';
import React,{useState,useEffect,useReducer,Component} from 'react';
import {useParams} from 'react-router-dom';
import logger from 'use-reducer-logger';



const reducer = (state,action) => {
      switch(action.type){
           case  'FETCH_REQUEST':
              return {...state,loading: true};
              case  'FETCH_SUCCESS':
               return {...state,product: action.payload,loading:false};
               case 'FETCH_FAIL':
                  return {...state,loading:false,error: action.payload};
                 default:
                  return state;
               }
   };

   
 
function ProductScreen(props){
            
     const params = useParams();
     
     const {_id} = params; 
     /*const [sizes,setSizes] = useState(-1);
     const handlerLoadingArticles = function(e){
      const option = e.target.value;
}   */
      

      const [{loading, error, product},dispatch] = useReducer(logger(reducer),{
            product: [],
            loading: true,
            error: '',
           }); 
          
         useEffect(()=>{
              const fetchData = async()=>{
               dispatch({type: 'FETCH_REQUEST'});
               try{
                  const result = await axios.get(`/api/products/${_id}`); 
                  dispatch({type: 'FETCH_SUCCESS',payload:result.data})
                  
               }catch(err){
                   dispatch({type: 'FETCH_FAIL', payload: err.message});
               }
                              
            };
              fetchData();
         },[_id]);
            
      return(
         <div>
         <div> 
       <Link to="/">Back to results</Link>
       <div className="product-report">
       
       <Link to={`/products/${product.name}`}>
       <img className="image" src={product.image} alt={product.name} ></img>      
       </Link>      
       
                 <div className="product-description">
                                   <div className="name-product">{product.name}</div>
                                   <div className="rating-product">{product.rating}</div>
                                   
                                   <div className="product-price-variation">
                                               <div className="product-price">Price:</div>
                                               <div className="variation-price">{product.price}</div>
                                   </div>

                                   

                                   <div className="product-size-variation">
                                               <div className="product-size">Size:</div>
                                               <div className="size-variation">
                                                      <select className="size-select" >
                                                      {
                                                               product.size.map((item,i)=>(
                                                                    <option value={i}>{item}</option>
                                                               ))

                                                               
                                                           }    
                                                      </select>                                        
                                               </div>
                                   </div>
                                 





                                              
                                                                    
                                   <div className="product-color-variation">
                                               <div className="color-product">Color:</div>
                                               <div className="color-variation">
                                                         
                                              </div>
                                   </div>

                                   
                 </div>
                 <div className="cart-box">
                               <h1 className="price-cart-box">$9.0</h1>
                               <h1 className="stock-cart-box">In Stock</h1>
                                           <div className="cart-box-buttons">
                                           <select className="select-button">
                                                           <option value="">Quantity</option>
                                                           <option value="1">1</option>
                                                           <option value="2">2</option>
                                                           <option value="3">3</option>
                                                           <option value="4">4</option>
                                                           <option value="5">5</option>
                                                           <option value="6">6</option>
                                                           <option value="7">7</option>
                                                           <option value="8">8</option>
                                                           <option value="9">9</option>
                                                           <option value="10">10</option>
                                           </select>
                                           <button className="cart-button">Add to cart</button>         
                                             
                                           </div> 
                 </div>   
       </div>         
    
   
</div>


  </div>
               
        )
  }

export default ProductScreen;

server

import express from 'express';
import data from './data.js';

const app = express();

app.get('/api/products',(req,res)=>{
    res.send(data.products);
});

app.get('/api/products/:name',(req,res)=>{
    const product = data.products.find((x)=>x.name==req.params.name);
    if(product){
        res.send(product);
    }else{
        res.status(404).send({message: 'Product Is Not Found'});
    }
});

const port = process.env.PORT || 5000;
app.listen(port, () => {
    console.log(`serve at http://localhost:${port}`);
})

data

export default {
    /*image: '/images/T-Shirt.jpg',*/
    products: [
      {
        _id:1,
        name: 'T-Shirt-Hurley',
        rating: 4.8,
        image: '/images/T-Shirt.jpg',
        price: '$20',
        size: ["Small","Medium","Large"],
        color: ["Red","Blue","Black","White"]
        },
        {
        _id:2,
        name: 'Jean-Levi',
        rating: 4.2,
        image: '/images/Jean.jpg',
        price: '$30',
        size: ["Small","Large"],
        color: ["Blue","Black","White"]
        },
        {
        _id:3,   
        name: 'Jacket-Quicksilver',
        rating: 4.5,
        image: '/images/Jacket.jpg',
        price: '$35',
        size: ["Medium","Large"],
        color: ["Blue","Black","White"]
        },
        {
        _id:4,
        name: 'T-Shirt-Adidas',
        rating: 4.8,
        image: '/images/T-Shirt-2.jpg',
        price: '$20',
        size: ["Small","Medium"],
        color: ["Red","Black","White"]
        },
        {
        _id:5,
        name: 'Jean-Wrangler',
        rating: 4.2,
        image: '/images/Jean-2.jpg',
        price: '$30',
        size: ["Medium"],
        color: ["Blue","White"]
        },
        {
        _id:6,
        name: 'Jacket-Champion',
        rating: 4.5,
        image: '/images/Jacket-2.jpg',
        price: '$35',
        size: ["Medium","Large"],
        color: ["Black","White"]
         }

        ]
      }

Result before refreshing:
![image|690x388](upload://opFVe9MIVwn8vnhTNXnjLB4wr2M.jpeg)



Result  after refreshing:
![image|690x388](upload://25qAZKNOm4wa7cdsy0dph09dSBq.png)

What is the full error message (including a line numbers?)

1 Like

Praise to the Lord, I have found the answer at Geminis. Let me get home and I will publish that here. I am thankful for your nice answer. I appreciate it.

please do not share AI generated content, it is against the forum rules

1 Like

It is not generated by AI. The code was developed by myself. You are going to notice it when you make the comparisons between the former code and the current one. (Thanks for the explanation because I was not aware of the rule.)

ProductScreen

import {Link} from 'react-router-dom';
import axios from 'axios';
import React,{useState,useEffect,useReducer,Component} from 'react';
import {useParams} from 'react-router-dom';
import logger from 'use-reducer-logger';
import Badge from 'react-bootsrap/Button';
{/*import Rating from '../components/Rating';
import {Helmet} from 'react-helmet-async';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';
import {getError} from '../utils';
import {Store} from '../Store'; */}


const reducer = (state,action) => {
      switch(action.type){
           case  'FETCH_REQUEST':
              return {...state,loading: true};
              case  'FETCH_SUCCESS':
               return {...state,product: action.payload,loading:false};
               case 'FETCH_FAIL':
                  return {...state,loading:false,error: action.payload};
                 default:
                  return state;
               }
   };

   
 
function ProductScreen(props){
            
     const params = useParams();
      const {_id} = params; 
      const [color, setColor] = React.useState(0);
      const [size, setSize] = React.useState(0);
      const [quantity, setQuantity] = React.useState(0);
      
      let varyOfColor=parseInt(color)+1;
      let varyOfSize=parseInt(size)+1;
      let varyOfQuantity=parseInt(quantity)+1
      let priceInFunctionOfColorAndSize=varyOfSize+varyOfColor;      
      
            
      const [{loading, error, product},dispatch] = useReducer(logger(reducer),{
            product: {},
            loading: true,
            error: '',
           }); 
          
      useEffect(()=>{
              const fetchData = async()=>{
               dispatch({type: 'FETCH_REQUEST'});
               try{
                  const result = await axios.get(`/api/products/${_id}`); 
                  dispatch({type: 'FETCH_SUCCESS',payload:result.data})
                  
               }catch(err){
                   dispatch({type: 'FETCH_FAIL', payload: err.message});
               }
                              
            };
              fetchData();
         },[_id]);
      
    {/* const {state,dispatch: ctxDispatch} = useContext();
      const addToCartHandler = () => {
           ctxDispatch({type: 'CART_ADD_ITEM', payload: {...product,quantity:1}})
      }*/}     
      
         return(
                loading?<div>Loading...</div>
                :error? <div>{error}</div>
                :
                 <div>
                              <div>
                                    <div> 
                                          {/*<Link to="/">Back to results</Link> */}  
                                                <div className="product-report">
                                                      <Link to={`/products/${product.name}`}>
                                                            <img className="image" src={product.image} alt={product.name} ></img>      
                                                      </Link>      
                                    <div className="product-description">
                                                      <div className="name-product">{product.name}</div>
                                                      <div className="rating-product">{product.rating}</div>
                                                      
                                                      <div className="product-price-variation">
                                                                  <div className="product-price">Price:</div>
                                                                  <div className="variation-price">{"$"+(product.price+priceInFunctionOfColorAndSize)*varyOfQuantity}</div>
                                                      </div>

                                                      

                                                      <div className="product-size-variation">
                                                                  <div className="product-size">Size:</div>
                                                                  <div className="size-variation">
                                                                  
                                                                  <select className="size-select-button" value={size} onChange={(event) => {setSize(event.target.value);}}>
                                                                              {
                                                                                          product.size && Array.isArray(product.size) ? (
                                                                                          product.size.map((item, i) => (
                                                                                          <option key={i} value={i}>
                                                                                                {item}
                                                                                          </option>
                                                                                                ))
                                                                                          ) : (
                                                                                                      <option value="">No sizes available</option>
                                                                                          )
                                                                                    }
                                                                        </select>
                                                                              {/*<p>
                                                                                    <strong>Current value:</strong>
                                                                                                {size}
                                                                              </p>*/}                                                 
                                                                  </div>
                                                      </div>
                                                      <div className="product-color-variation">
                                                                  <div className="color-product">Color:</div>
                                                                  <div className="color-variation">
                                                                  <select className="color-select-button" value={color} onChange={(event) => {setColor(event.target.value);}}>
                                                                        {
                                                                        product.size && Array.isArray(product.size) ? (
                                                                              product.color.map((item, i) => (
                                                                                    <option key={i} value={i}>
                                                                                    {item}
                                                                                    </option>
                                                                                    ))
                                                                        ) : (
                                                                              <option value="">No sizes available</option>
                                                                              )
                                                                              }
                                                                        </select>
                                                                  {/* <p>
                                                                        <strong>Current value:</strong>
                                                                                                            {color}
                                                                        </p>*/}     
                                                                  </div>
                                                      </div>

                                                      
                                    </div>
                                    <div className="cart-box">
                                                      <h1 className="price-cart-box">{"$"+(product.price+priceInFunctionOfColorAndSize)*varyOfQuantity}</h1>
                                                      <h1 className="stock-cart-box">In Stock</h1>
                                                                  <div className="cart-box-buttons">
                                                                  <select className="quantity-select-button" value={quantity} onChange={(event) => {setQuantity(event.target.value);}}>
                                                                        {
                                                                        product.quantity && Array.isArray(product.quantity) ? (
                                                                              product.quantity.map((item, i) => (
                                                                                    <option key={i} value={i}>
                                                                                    {item}
                                                                                    </option>
                                                                                    ))
                                                                        ) : (
                                                                              <option value="">No sizes available</option>
                                                                              )
                                                                              }
                                                                        </select>
                                                                 {/* <button className="cart-button" onClick={addToCartHandler}>Add to cart</button>*/}
                                                                  <button className="cart-button">Add to cart</button>          
                                                                  
                                                                  </div> 
                                          </div>   
                              </div>         
                              </div>

                              </div>
                </div>
         );
  }

export default ProductScreen;

data

export default {
    /*image: '/images/T-Shirt.jpg',*/
    products: [
        {
        _id:1,
        name: 'T-Shirt-Hurley',
        rating: 4.8,
        image: './images/T-Shirt.jpg',
        price: '$20'
        },
        {
        _id:2,
        name: 'Jean-Levi',
        rating: 4.2,
        image: '/images/Jean.jpg',
        price: '$30'
        },
        {
        _id:3,   
        name: 'Jacket-Quicksilver',
        rating: 4.5,
        image: '/images/Jacket.jpg',
        price: '$35'
        },
        {
        _id:4,
        name: 'T-Shirt-Adidas',
        rating: 4.8,
        image: '/images/T-Shirt-2.jpg',
        price: '$20'
        },
        {
        _id:5,
        name: 'Jean-Wrangler',
        rating: 4.2,
        image: '/images/Jean-2.jpg',
        price: '$30'
        },
        {
        _id:6,
        name: 'Jacket-Champion',
        rating: 4.5,
        image: '/images/Jacket-2.jpg',
        price: '$35'
         }

        ]
      }

Home Screen

import React,{useState,useReducer,useEffect} from 'react';
import {Link } from 'react-router-dom';
import axios from 'axios';
import logger from 'use-reducer-logger';

const reducer = (state,action) => {
   switch(action.type){
        case  'FETCH_REQUEST':
           return {...state,loading: true};
           case  'FETCH_SUCCESS':
            return {...state,products: action.payload,loading:false};
            case 'FETCH_FAIL':
               return {...state,loading:false,error: action.payload};
              default:
               return state;
            }
};

function HomeScreen(){
   const [{loading, error, products},dispatch] = useReducer(logger(reducer),{
      products: [],
      loading: true,
      error: '',
     }); 
    
   useEffect(()=>{
        const fetchData = async()=>{
         dispatch({type: 'FETCH_REQUEST'});
         try{
            const result = await axios.get('/api/products'); 
            dispatch({type: 'FETCH_SUCCESS',payload:result.data})
            
         }catch(err){
             dispatch({type: 'FETCH_FAIL', payload: err.message});
         }
         const result = await axios.get('/api/products');
         
      };
        fetchData();
   },[]);
      return (
         loading?<div>Loading...</div>
         :error? <div>{error}</div>
         :
          <div>
                  <body>
                        <nav>
                              <div className="menu-background">
                                    {/*<p className="menu" >Amazonas</p>*/}
                                     <Link to="/" className="menu" >amazonas</Link>

                              </div>
                              <div className="logo-background">
                                                   <p className="logo">Menu</p>
                              </div>
                        </nav>
                        <ul className="products">
                                                {
                           products.map(product=>
                           <li>
                              <div className="product">
                                 <Link to={`/product/${product.name}`}>
                                       <img className="image" src={product.image} alt={product.name} ></img>
                                 </Link>
                                 <Link to={`/product/${product.name}`}>{product.name}</Link>
                                       <div className="rating">{product.rating}</div>
                                       <div className="price">{"$"+product.price}</div>
                                 </div>
                           </li>        
                           )
                           }
                           </ul>
               </body>
      </div>
             )          
           }
export default HomeScreen;




The problem was caused by bad initialization. The const [{loading, error, product},dispatch] was initialized as (an array) instead of being initilized as an {} (an object).

Because it was receiving an array instead of receiving an object, it was needed two conditions. There was a product and it was an array. That is the reason why of those conditionals. Everything is in a ternary conditional because that is the way we can work in React. It was hard to get this explanation.

That is the problem when you follow a tutorial instead of knowing what you are doing. I tried to read the documentation , it did not answer my question.

This is the source of the tutorial: https://www.youtube.com/watch?v=CDtPMR5y0QU&t=8883s