'Getting this error: extraccion.map is not a function

I'm trying to display data from a mysql table in a react page, but I don't understand why this error appears. I get my data this way:

while($fila = mysqli_fetch_array($ejecutar)) {
$array[] = array(
  "titulo" => $fila['titulo'],
  "tipo" => $fila['tipo'],
  "tamanio" => $fila['tamanio'],
  "fecha" => $fila['fecha'] ); }

 $json = json_encode($array);

 echo $json;

After requesting it with an axios request:

const obtenerArchivos = async () => {

console.log('Clase obtenerArchivos ejecutada')
const res = await axios.get('http://localhost/AdaptStorage/mostrarDatos.php');
setExtraccion(res.data);
console.log(res.data);
    
}

And then I try to show it with the map function:

{  
              extraccion.map(item=>{
                return(
                
                <tr style={{ borderBottom: "solid 0.05rem #bbb" }}>
                <th scope="row" style={{ fontWeight: 600 }}>
                </th>
                <td style={{ fontWeight: 400 }}>{item.titulo}</td>
                <td style={{ fontWeight: 400 }}>28/09/21</td>
                <td style={{ fontWeight: 400 }}>230 KB</td>
                <td
                  style={{
                    fontWeight: 400,
                    whiteSpace: "nowrap",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                  }}
                >
                  
                </td>
              </tr>
              );
              })}

This is the content of extraccion: content of extraccion

I tried this function and it seems that extraccion is not an array:

if(!Array.isArray(extraccion)) return console.log('extraccion is not 
array')

extraccion is not array



Solution 1:[1]

  1. Please check type of the API result by axios to confirm the data type from backend API.
 console.log(typeof res.data);
  1. If this is not an array, you need to fix your backend script. Make sure backend API returns the JSON data correctly. If the backend API result is not JSON format, you can fix it by adding the JSON response header on your backend script.
header("Content-Type: application/json; charset=UTF-8");
  1. On frontend rendering, please try to add the following code to prevent null before using map function.

Because if the extraccion is a state variable, it would initially be undefined in case that you defined it like const [extraccion, setExtraccion] = useState()

{ 
extraccion && extraction.map(... ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Liki Crus