Home > OS >  Set value that comes from an API
Set value that comes from an API

Time:07-23

I bring from the back an array of objects, where one of those objects has a property called temperament, this property saves a value of type String, example: "Happy, Playful, Friendly". My idea is to place this same String but in the following way: "Happy | Playful | Friendly". From a card component I have tried to do the following

/*let temperament2;
if(!createInDb){
     temperament2 = temperament.replaceAll(',','|');
} */
//console.log(temperament)
return(
    <div className="container">
        <img src={image} width="80px" height="80px" alt=""/>
        <h2>{name}</h2>
        <h3>{temperament}</h3>
        <h3>{weight}</h3>
        <h3>{!!createInDb?"true":"false"}</h3>

    </div>
)

I have tried to do it directly from the , I have also tried to do it from the back:

let dog = dogs.data.map(el =>{
        temp = el.temperament.replaceAll(',','|')
        return{
            id:el.id,
            name:el.name,
            weight:el.weight.metric,
            height:el.height.metric,
            temperament:temp,
            image: el.image.url,
            life_span: el.life_span
        }
    })

and neither, I have tried to modify the name property and with success, but I can't do it with the temp property. I don't quite understand where I'm going wrong. I leave the API to where I am making the request Codesandbox Demo


import { useEffect, useState } from "react";

export default function App() {
  const [dog, setDog] = useState([]);

  const fetchData = async () => {
    const response = await fetch("https://api.thedogapi.com/v1/breeds");
    const data = await response.json();
    setDog(data);
  };
  
  useEffect(() => {
    fetchData();
  }, []);
  
  return (
    <>
      {dog &&
        Object.entries(dog).map(([key, val]) => (
          <div className="container" key={key}>
            <img src={val.image.url} width="80" height="80" alt="" />
            <h1>{key}</h1>
            <h2>{val.name}</h2>
            <h3>{val.temperament?.replaceAll(",", " | ")}</h3>
            <h3>{`W Imperial: ${val.weight.imperial}, W Metric: ${val.weight.metric}`}</h3>
            <h3>{`H Imperial: ${val.height.imperial}, H Metric: ${val.height.metric}`}</h3>
            <h4>{val.life_span}</h4>
            <br />
            <br />
          </div>
        ))}
    </>
  );
}
  • Related