Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
34
rated 0 times [  40] [ 6]  / answers: 1 / hits: 19693  / 6 Years ago, tue, december 4, 2018, 12:00:00

TL;DR: I'm trying to use the new react-hooks api, but I keep getting an Invariant Violation error when calling the setState hook, but it keeps failing.



import React, { useState } from 'react';

// type State = {
// heading: string;
// }

const Text = () => {
const initialState = 'Heading'.toUpperCase();

const [heading, setHeading] = useState(initialState);

return (
<header>
<h1>
{setHeading('Brussels')};
{heading}
</h1>
</header>
);
};

export default Text;

More From » reactjs

 Answers
15

Calling setHeading(Brussel) will cause re rendering again and again which in turns result in an infinite loop, to prevent that you need an event to change the header from Heading to Brussels.
Below code might help you



const Text = () => {
const initialState= 'Heading'.toUpperCase();
const [heading, setHeading] = useState(initialState);
return (
<header>
<h1>
{heading}
<button onClick= {() =>{setHeading(Brussel)}}>ChangeName</button>
</h1>
</header>
);
};

[#52983] Thursday, November 29, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devinjadong

Total Points: 711
Total Questions: 117
Total Answers: 100

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
;