0

The returned JSON has a structure like this:

{
    "endocrinologist": {
        "en_name": "Endocrinologist",
    },
    "dermatologist": {
        "en_name": "Dermatologist",
    },
    "dentis": {
        "en_name": "Dentist",
    },
    "neurosurgeon-brain-spine": {
        "en_name": "Neurosurgeon (Brain & Spine)",
    },
}

I have a services .js file where I'mfetching the data and returning it like:

function getList() {

    let fullURL = MY_FULL_URL

    return new Promise((res, rej) => {
        try {
            axios.get(fullURL).then((response) => {
                res(response.data)
            })
        } catch (error) {
            rej(error)
            alert(error)
        }
    })
}

The in the class where I want to render the component based on the fetched data goes like this:

const [meds, setMeds] = useState([])

    async function getMedList() {

        const resp = await bookingServices.getList()
        setMeds(resp)

    }

    useEffect(() => {
        getMedList()
    }, [])

...

                {meds.map((s, i) =>
                    <MedsCard title={s.en_name} />
                )}

When I run the app I get

TypeError: undefined is not a function (near '...meds.map...')

I tried one solution which was to change setMeds(resp) to setMeds(JSON.parse(resp)) as the JSON I'm getting is a single object, inside o which I've other single objects. This stopped the error but I get this

Possible Unhandled Promise Rejection (id: 10): SyntaxError: JSON Parse error: Unexpected identifier "object"

So, how do I correctly parse this JSON?

Chaudhry Talha
  • 7,231
  • 11
  • 67
  • 116

1 Answers1

0

Render the result of Object.values(meds):

Object.values(meds).map(({ en_name }) =>
  <MedsCard title={en_name} />
)

Full React function component example:

const { useEffect, useState } = React;

const sampleJsonData = {
  "endocrinologist": { "en_name": "Endocrinologist" },
  "dermatologist": { "en_name": "Dermatologist" },
  "dentis": { "en_name": "Dentist" },
  "neurosurgeon-brain-spine": { "en_name": "Neurosurgeon (Brain & Spine)" },
};

class BookingService {
  getList() {
    return Promise.resolve(sampleJsonData);
  }
}

const bookingServices = new BookingService();

const MedsCard = (props) => {
  const { title } = props;
  return (
    <div className="MedsCard">
      <span className="CardTitle">{title}</span>
    </div>
  );
};

const App = () => {
  const [meds, setMeds] = useState([]);

  useEffect(() => {
    bookingServices.getList().then(setMeds);
  }, []);

  return (
    <div className="App">
      {Object.values(meds).map(({ en_name }) =>
        <MedsCard title={en_name} />
      )}
    </div>
  );
};

// Render it
ReactDOM.render(<App />, document.getElementById("react"));
.App {
  display: flex;
  flex-direction: column;
}

.MedsCard {
  display: flex;
  border: thin solid grey;
  padding: 0.5em;
  margin-bottom: 0.25em;
}

.MedsCard > .CardTitle {
  font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132