How can I fix the Axios get request and the React Hooks?

Viewed 137

Details about my goal:

I want to create a React App with Material UI that detects gender on the basis of your name.

Summary of the problem:

  • I am not getting back the result for the name that is entered into the input field

  • Expected Result:

    • {name: "Alice" gender: "female", probability: 0.83, count: 3387}
  • Actual Result:

    • null
    • undefined
    • {data: "Data was undefined"}

Useful resources for this issue:

2 Answers

I think your code is a little over-engineered, and doesn't properly handle the asynchronous nature of the request.

What I typically do is return the fetch or axios object so that the calling component can wait for the response and handle it when it's ready.

Forked example

As you can see, I've removed a couple of pieces from your Container.jsx component (which might need a different name fwiw).

Instead of setting a flag for the form being ready to submit, I just have the button directly calling the fetchNameData function.

The checkGender function from your utilities function now directly returns the axios object, which is a promise. The fetchNameData function is async so it can wait for the results from this promise.

The code works fine, if the name starts with a lowercase, it will throw an error, so what you can do is capitalize the first letter of the user input enter image description here

Related