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

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:
This is the link to the CodeSandBox for this problem: click here --see what I have tried
Gender.io API link (I used this API to detect gender): click here
Material UI for React: click here

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

Related

Is it normal in React to use `useState` to manage whether a form has been submitted?

A basic online React tutorial is demonstrating how to create a React-based form with 3 fields (first name, last name, and email). Surprisingly to me, it has useState to manage whether or not a form has been submitted, which it uses to decide on whether to show a success message or not.
Please note that it does NOT make an actual form submission (i.e. no API calls) and so I am wondering whether it is using state only for simulation purposes here.
Here is a snippet:
const [submitted, setSubmitted] = useState(false);
...
{submitted && !values.lastName && <span id='last-name-error'>Please enter a last name</span>}
...
{showSuccess && <div class='success-message'>Success! Thank you for registering</div>}
...
Is it normal for real-world React applications to useState to manage whether or not a simple form such as 'contact us' or 'feedback', etc, has been submitted? My guess is that normally there would be no need to do so.
As the resulting API call, whether 'success' or 'fail' could simply be used to show the state of the error message. Thereafter, the form should ideally reset itself to allow for another submission. So, there would be no need to store the state of the submitted form. Am I correct in my understanding?
Your question is a little confusing. basically if you want to store a data in React and this data has direct effect on your application you mostly should save it in state. When you submit a form, the form onSubmit event handler will be called and you can do everything in that event handler. It's clear that in the tutorial submitted state is a flag to simulate the fetch process. Usually when you want to handle submitting a form and fetching API you should store 2 items in state:
Error and Loading
You should use loading flag to show a loading indicator during fetching API and use error to check if any error exist store and show it. If API fetches successfully you may redirect user to another page, show a notification or change some data in your state. It's up to you. But be sure the submitted state in your tutorial is just an example ans simulation. But it has real usages in real world! Hope it helps!
Here is an example: I want to add a user by fetching an api and i want if api fetches successfully add it to the list:
Sandbox

ReactJS Function Components object updates on second time

I have a login page(Functional Component), When a user tries to login without entering the required fields, I have to show the error message(ex:"Email is required"). When an invalid field exists, I shouldn't make the API call.
But, without entering fields, when I click on login button, API call is done. Again clicking on login button stops the API call.
I have made this demo - https://stackblitz.com/edit/react-pd6vvk?file=login.js which explains the issue.
Steps to follow:
1.Click on login without filling any text values. You can see "API request made" statement when fields are invalid.
2.Again click on login button, "API Request stopped" statement is displayed now.
I am new to React and I don't know, the reason and the solution to fix this issue.
Can somebody please help me out?
Thank you,
Abhilash
Because, setValidFields has async behaviour :
validateLoginForm(); //<--- inside this setValidFieldsis async
console.log(validFields);
if (isFormValid()) { //<---- so,this will still have true value ( means not updated )
// inside validateLoginForm()
// this state change won,t be reflected immediately
setValidFields(validFields => ({
...validFields,
[key]: error.length == 0
}));
I have made few changes as per your code structure, as long as I know you will need useEffect also as shown in working demo.
WORKING DEMO

Api result isn't being rendered to page

I'm using the pokeapi to return basic information about a pokemon from the pokeapi. Nothing is being rendered to the component. Not even the default value passed as a parameter(pikachu). When I inpspect the XHR response with the dev tools, a response object is being returned but it's not being displayed. Any suggestions?
I have a link to the sandbox code.
https://codesandbox.io/s/blissful-mountain-jvbwc?file=undefined
Ahh i see the issue
You need to change your searchPokemon method to use an arrow function because non-arrow functions are not this binding.
Another issue, you should update you catch statement to use console.error so you can see the error message in the console.

Clicking navigation button in Puppeteer returns null response? How to see which function is being clicked?

I'm trying to test clicking a button on a registration app to make sure that the page correctly navigates to the right page.
When I console.log out response in the code it returns an array that looks like this
[undefined, null]
However when I take a screenshot of the page or check the url, the click and navigation worked. It is on the correct page.
I don't understand why this is returning undefined/null. Also, I could not figure out how to test which function was being called when you click on the button.
I wanted to be able to see the actual function that is being called.
I'm using AngularJS 1.6, Mocha, Puppeteer 1.11, and Node 6.4.0
I'm also a junior dev so it could be something simple that I just didn't understand, please help!
it('should rederict to guest_sms_code state when clicking \'I have a guest code\'', async (function () {
var response = await (Promise.all([
page.waitForNavigation({waitUntil: 'domcontentloaded'}),
page.click('[ng-click="enterSmsCode()"]'),
]));
var url = await (page.url());
if (url.indexOf('guest_sms_code') === -1) {
assert.ok(false, 'The URL does not contain \'guest_sms_code\'')
}
}))
I'm not convinced that you can tell which method is called from a UI test. That's something that a JavaScript unit test can prove using, say, something like Mocha or Jest to test your codes behaviour. However an automated UI test, from my experience, won't tell you that. After all, you're trying to hide the inner workings of your app from an external user, right?
As for why the Promise.all([]) call is returning [undefined, null], well I can at least help you with that.
Firstly, you should have a look at the API documentation for both methods you've invoked in your test:
waitForNavigation docs: https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagewaitfornavigationoptions
click docs: https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pageclickselector-options
In the case of waitForNavigation the response actually returns a Promise which may or may not have a Response value. Whether any data is returned with that Response is dependent on the navigation that occurs in the UI. In your case, you're seeing that undefined value in your array to indicate that there has not been any Response data returned from the navigation.
For the click method, this also just returns a resolved or rejected Promise with no data of any kind returned. So, naturally, you've no actual value returned here at all hence the null value being pushed to the array.

React App - Issues Calling 3rd Party API on First Try

I have a react app that lets a user choose from LIs to get search results from a 3rd party API based on which LI they choose. The LI has a click handler that, as part of it, makes an API request to the 3rd party. The first time they click the LI, the value is null, even though it should be a piece of the React state. This is part of the click handler function:
let choice = event.currentTarget.innerText;
this.setState({inputVal: choice});
let urlquery = this.state.inputVal
console.log(urlquery);
The first time that LI is clicked, the console.log returns null. The second time you click it, you get back the correct value. Any suggestions on how to fix this?
Thanks
The state has not been updated when your let urlquery = this.state.inputVal line is run. Calls to setState(...) are asynchronous. Reference the react docs regarding setState(...) here: https://reactjs.org/docs/react-component.html#setstate
Your options to deal with this are to use the second parameter of setState(...), which is a callback which runs after setState has actually updated the state, or using componentDidUpdate. Both are mentioned in the docs referenced above.

Resources