Aspnetcore.docs: Unable to use useState hook with .net core project template

Created on 14 May 2019  Â·  5Comments  Â·  Source: dotnet/AspNetCore.Docs

Moved from @mookhoo on https://github.com/aspnet/AspNetCore.Docs/issues/12405 ...

I am trying to create a new page that utilizes useState hook in the project created by this template, I have been unsuccessful. I have tried several ways, creating a function, and I end up getting error. Do you have an example on how to create a new page in this template and utilize "useState" hook? Thanks!


Document Details

⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

P2 PU Source - Docs.ms product-question

All 5 comments

At the time of writing the default ClientApp project doesn't support it. You can upgrade the create-react-app manually. I did that by deleting node_modules, updating the package.json, and do npm install in the ClientApp folder.
The package.json I used:
{
"name": "just-a-project",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1"
},
"eslintConfig": {
"extends": "react-app"
},
"scripts": {
"start": "rimraf ./build && react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

This does not answer my question.

I am unable to utilize useState or useEffect because these hooks can only be used within a function. However, the project utilizes class by extending Component. Converting the class into a function throws errors for other methods that are utilized in the project. I hope this clarifies the issue I am facing, and hoping for a solution/suggestion.

import React from 'react';

export function Counter(props) {
const [currentCount, incrementCounter] = React.useState(0);

return (


Counter

  <p>This is a simple example of a React component.</p>

  <p>Current count: <strong>{currentCount}</strong></p>

  <button className="btn btn-primary" onClick={() => incrementCounter(currentCount + 1)}>Increment</button>
</div>

);
}

Thanks for contacting us. We believe that the question you've raised have been answered. If you still feel a need to continue the discussion, feel free to reopen it and add your comments.

Was this page helpful?
0 / 5 - 0 ratings