• Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

type error = assignment to constant variable react.js

the error is in 7th line of the code

i am a totally new beginner so it would be helpful if you explain it to me

  • react-hooks

user14299934's user avatar

  • 1 why yu declare let input = <input ... in return? –  Viet Commented Jun 15, 2021 at 9:27
  • You are trying to override the const value, that is causing the issue –  Sarun UK Commented Jun 15, 2021 at 9:33
  • Please explain your use-case –  Sarun UK Commented Jun 15, 2021 at 9:34
  • remove equal operator on line 7 => set_todos([...todos,input]); –  Khawar Qureshi Commented Jun 15, 2021 at 9:39

2 Answers 2

If you want to update your state (that is an array) in react hooks, you should try like this :

with this code, you will not see any error but I have some offer for your code that make it better:

  • put your inputs such as input and buttons in the form tag
  • use variable declarations outside of return ( let return be for HTML tag and its better to use your logics outside of return ) make it easier to read

and I think your code can be like this:

reza makhdomi's user avatar

You should use set_todos like below:

Because set_todos is a function. You can find the State Hook's usage in Introducing Hooks .

Skyyye's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged reactjs react-hooks or ask your own question .

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • What is this houseplant with a red fleshy stem and thick waxy leaves?
  • How to read data from Philips P2000C over its serial port to a modern computer?
  • Age is just a number!
  • Dial “M” for murder
  • How to Increase a Length in Inches by a Point without Manual Conversion?
  • What is the meaning of "Exit, pursued by a bear"?
  • Power line crossing data lines via the ground plane
  • Many and Many of - a subtle difference in meaning?
  • Guitar amplifier placement for live band
  • Can a Statute of Limitations claim be rejected by the court?
  • Why is this white line between the two vertical boxes?
  • Does the Ghost achievement require no kills?
  • How to handle stealth before combat starts?
  • A study on the speed of gravity
  • Sulphur smell in Hot water only
  • Including standalone tikz in beamer
  • Cover letter format in Germany
  • How is lost ammonia replaced aboard the ISS?
  • How would a culture living in an extremely vertical environment deal with dead bodies?
  • Does the First Amendment protect deliberately publicizing the incorrect date for an election?
  • Convert a Dataset into a list of lists and back to a Dataset
  • Rendering React SPAs within Salesforce
  • MOSFETs keep shorting way below rated current
  • Cleveref, biblatex and automatic equation numbering

react js assignment to constant variable

TypeError: Assignment to Constant Variable in JavaScript

avatar

Last updated: Mar 2, 2024 Reading time · 3 min

banner

# TypeError: Assignment to Constant Variable in JavaScript

The "Assignment to constant variable" error occurs when trying to reassign or redeclare a variable declared using the const keyword.

When a variable is declared using const , it cannot be reassigned or redeclared.

assignment to constant variable

Here is an example of how the error occurs.

type error assignment to constant variable

# Declare the variable using let instead of const

To solve the "TypeError: Assignment to constant variable" error, declare the variable using the let keyword instead of using const .

Variables declared using the let keyword can be reassigned.

We used the let keyword to declare the variable in the example.

Variables declared using let can be reassigned, as opposed to variables declared using const .

You can also use the var keyword in a similar way. However, using var in newer projects is discouraged.

# Pick a different name for the variable

Alternatively, you can declare a new variable using the const keyword and use a different name.

pick different name for the variable

We declared a variable with a different name to resolve the issue.

The two variables no longer clash, so the "assignment to constant" variable error is no longer raised.

# Declaring a const variable with the same name in a different scope

You can also declare a const variable with the same name in a different scope, e.g. in a function or an if block.

declaring const variable with the same name in different scope

The if statement and the function have different scopes, so we can declare a variable with the same name in all 3 scopes.

However, this prevents us from accessing the variable from the outer scope.

# The const keyword doesn't make objects immutable

Note that the const keyword prevents us from reassigning or redeclaring a variable, but it doesn't make objects or arrays immutable.

const keyword does not make objects immutable

We declared an obj variable using the const keyword. The variable stores an object.

Notice that we are able to directly change the value of the name property even though the variable was declared using const .

The behavior is the same when working with arrays.

Even though we declared the arr variable using the const keyword, we are able to directly change the values of the array elements.

The const keyword prevents us from reassigning the variable, but it doesn't make objects and arrays immutable.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • SyntaxError: Unterminated string constant in JavaScript
  • TypeError (intermediate value)(...) is not a function in JS

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

TypeError: invalid assignment to const "x"

The JavaScript exception "invalid assignment to const" occurs when it was attempted to alter a constant value. JavaScript const declarations can't be re-assigned or redeclared.

What went wrong?

A constant is a value that cannot be altered by the program during normal execution. It cannot change through re-assignment, and it can't be redeclared. In JavaScript, constants are declared using the const keyword.

Invalid redeclaration

Assigning a value to the same constant name in the same block-scope will throw.

Fixing the error

There are multiple options to fix this error. Check what was intended to be achieved with the constant in question.

If you meant to declare another constant, pick another name and re-name. This constant name is already taken in this scope.

const, let or var?

Do not use const if you weren't meaning to declare a constant. Maybe you meant to declare a block-scoped variable with let or global variable with var .

Check if you are in the correct scope. Should this constant appear in this scope or was it meant to appear in a function, for example?

const and immutability

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in case the content is an object, this means the object itself can still be altered. This means that you can't mutate the value stored in a variable:

But you can mutate the properties in a variable:

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeError: Assignment to constant variable. #16211

@lidaof

lidaof commented Jul 25, 2019

or report a ?
bug

TypeError: Assignment to constant variable.

System: OSX
npm: 6.10.2
node: v10.13.0
react: 16.8.6

@artuross

artuross commented Jul 26, 2019 • edited Loading

What I think you're trying to is something like this:

something = 1; something = 2;

Even though the path implies that the error happens in react, I think the error happens in your code, but it's difficult to tell from a single line. Perhaps you could share a little bit more (error stack)?

Sorry, something went wrong.

lidaof commented Jul 26, 2019

Hi , thank you so much for reply. Sure, here is the screenshot:

I don't think I did that const thing....my code is

@jquense

jquense commented Jul 26, 2019

the error is coming from your code so there is either a typo/bug in what you've written or a problem compiling it. In either case it's not realted to React, and the React issue tracker is for React bugs. I'd recommend bisecting your code, commenting out bits and pieces until the error goes away and you can narrow down which part specifically is breaking it.

@jquense

Hi ok....so the problem only happens on build version, it's not happening in development version.......so the code should be fine....

artuross commented Jul 27, 2019

I would look at lines 112 and 126 at .

@shahchaitanya

shahchaitanya commented Jul 29, 2019

I am facing a similar issue today. did you find out a solution to fix it?

lidaof commented Jul 29, 2019

I am not sure if we have same condition, I updated typescript to 3.4 and create-react-app to 2.1 solved this problem.

  • 👍 1 reaction

are you using uglify js plugin in Production? This problem is occurred due to this plugin. are referred to this bug. I solved this issue by adding in uglify js object.

  • 👍 3 reactions
  • 🎉 2 reactions
  • ❤️ 4 reactions
  • 🚀 1 reaction

lidaof commented Jul 30, 2019

Thank you for reply . I think i did use it, but I don't know where to put this option. I was using react-app-rewire with react-scripts-ts

shahchaitanya commented Jul 30, 2019

you can configure your web pack in webpack.config.js file. I put this option under webpack.config.js.

thank you . I tried that but it's not working for me. Thanks again.

@prasenpatil2107

prasenpatil2107 commented Oct 10, 2019

I think there is a simple catch.....if you define it as const you cant change its value. To resolve it just define it by let and try. I was going through a similar error solved it by this.

  • 👍 2 reactions
  • 👎 9 reactions

@jannunen

jannunen commented Sep 18, 2021

You just saved my day (after 10 hours of fiddling).

@ghost

ghost commented Oct 25, 2021

Knock Knock, I am also facing the same problem. 😄

  • 😄 1 reaction

No branches or pull requests

@jannunen

TypeError: Assignment to constant variable when using React useState hook

Abstract: Learn about the common error 'TypeError: Assignment to constant variable' that occurs when using the React useState hook in JavaScript. Understand the cause of the error and how to resolve it effectively.

If you are a React developer, you have probably come across the useState hook, which is a powerful feature that allows you to manage state in functional components. However, there may be times when you encounter a TypeError: Assignment to constant variable error while using the useState hook. In this article, we will explore the possible causes of this error and how to resolve it.

Understanding the Error

The TypeError: Assignment to constant variable error occurs when you attempt to update the value of a constant variable that is declared using the const keyword. In React, when you use the useState hook, it returns an array with two elements: the current state value and a function to update the state value. If you mistakenly try to assign a new value to the state variable directly, you will encounter this error.

Common Causes

There are a few common causes for this error:

  • Forgetting to invoke the state update function: When using the useState hook, you need to call the state update function to update the state value. For example, instead of stateVariable = newValue , you should use setStateVariable(newValue) . Forgetting to invoke the function will result in the TypeError: Assignment to constant variable error.
  • Using the wrong state update function: If you have multiple state variables in your component, make sure you are using the correct state update function for each variable. Mixing up the state update functions can lead to this error.
  • Declaring the state variable inside a loop or conditional statement: If you declare the state variable inside a loop or conditional statement, it will be re-initialized on each iteration or when the condition changes. This can cause the TypeError: Assignment to constant variable error if you try to update the state value.

Resolving the Error

To resolve the TypeError: Assignment to constant variable error, you need to ensure that you are using the state update function correctly and that you are not re-declaring the state variable inside a loop or conditional statement.

If you are forgetting to invoke the state update function, make sure to add parentheses after the function name when updating the state value. For example, change stateVariable = newValue to setStateVariable(newValue) .

If you have multiple state variables, double-check that you are using the correct state update function for each variable. Using the wrong function can result in the error. Make sure to match the state variable name with the corresponding update function.

Lastly, if you have declared the state variable inside a loop or conditional statement, consider moving the declaration outside of the loop or conditional statement. This ensures that the state variable is not re-initialized on each iteration or when the condition changes.

The TypeError: Assignment to constant variable error is a common mistake when using the useState hook in React. By understanding the causes of this error and following the suggested resolutions, you can overcome this issue and effectively manage state in your React applications.

References
[1] React Documentation:
[2] MDN Web Docs:

Tags: :  javascript reactjs react-state

Latest news

  • Google Play Console: Unavailability - Request Upload Key Reset
  • Fixing Bug: Embedding third-party API of Chess.com in WordPress LMS
  • Phone Number Verification on Kaggle: Initiating OTP Request
  • SVG Symbol Not Rendering in Vue3 Vite: One Icon Failing
  • Semantic Tag Usage: Dividing Header into Three Parts for Software Development Sites
  • Solving the Issue of Unfocused Input Fields with 'Cannot Type' Alerts in Software Development
  • CentOS 8: Unable to Find Updates - AppStream
  • Sending New Line Breaks in WhatsApp API Messages: A PHP Challenge
  • Resolving 403 Forbidden Errors with Spring Security in Learning Projects
  • Using Error Or Value Objects in Title Value Object Creation for a Simple Todo App
  • Reading a Text File in Java for Android Site Server
  • Resolving JavaScript Integration Issues in Food Menu Pricing App
  • Creating a Scrollable Small Widget in GTKMM4
  • Setting Middleware with User Configuration in ASP.NET Core App
  • Node.js and Firebase: Performing Add/Update Operations with Array References in Firestore
  • Error: ADB: Device Emulator-5554 Not Found in Android Instrumentation Tests
  • Contributing to Open-Source Golang Projects: Suggestions for Beginners
  • Speed Training: Random Forest Regression vs. SVR for Bitcoin Price Prediction
  • Troubleshooting a Fatal Error in XAMPP: A 3-Day Long Mystery
  • Telegram API: Special Character in Message Causes Bad Request
  • Understanding Positional Arguments vs. Keyword Arguments in Python with yfinance
  • Solving Project Euler 101: Matrix Magic
  • Recovering Deleted Google Drive Data for Photo Editing
  • Ubuntu: Chrome Fails to Render Glyphs
  • pnpm Monorepo Error: Peer Dependencies and Rollup Import Resolution
  • Interface 4.3 TFTLCD (PCB4301MSV1.1) with ESP32 using TFT_eSPILibrary: Display Connection Issues
  • Flutter Xcode Build Forever Stuck During Upgrade: A Common Issue
  • Verifying Old Electrum Bitcoin Wallet: Hash Seed Derivation Steps
  • Enhancing Chatbot Design: LLM Integration of Structured Activities
  • Completing Implementation of Google Mobile Ads SDK in Flutter Project for Google Analytics
  • Passing Data Between Processes with ByteBuffer, DirectBuffer, and Parcel in Java: Avoiding Temporary Array Copies
  • Applying Group Transform with Median Value in Pandas
  • Variable Syntax in Azure DevOps YAML Pipeline: Loop and Replace
  • Evaluating the Best Approach to GraphRAG Pipeline using Metrics
  • Configuring PingFederate Settings for Authorization Code Grant Flow using Postman with OAuth2.0 and OpenID Connect

React Tutorial

React hooks, react exercises, react es6 variables.

Before ES6 there was only one way of defining your variables: with the var keyword. If you did not define them, they would be assigned to the global object. Unless you were in strict mode, then you would get an error if your variables were undefined.

Now, with ES6, there are three ways of defining your variables: var , let , and const .

If you use var outside of a function, it belongs to the global scope.

If you use var inside of a function, it belongs to that function.

If you use var inside of a block, i.e. a for loop, the variable is still available outside of that block.

var has a function scope, not a block scope.

let is the block scoped version of var , and is limited to the block (or expression) where it is defined.

If you use let inside of a block, i.e. a for loop, the variable is only available inside of that loop.

let has a block scope.

Get Certified!

const is a variable that once it has been created, its value can never change.

const has a block scope.

The keyword const is a bit misleading.

It does not define a constant value. It defines a constant reference to a value.

Because of this you can NOT:

  • Reassign a constant value
  • Reassign a constant array
  • Reassign a constant object

But you CAN:

  • Change the elements of constant array
  • Change the properties of constant object

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

How to define constants in React?

In this article, we explain how to define and use constants in React to make your code more maintainable and reusable.

In React, you can define constants using the const keyword. For example:

This creates a constant named MY_CONSTANT with the value "hello". Constants are like variables, except that their value cannot be changed once they are assigned.

You can use constants in React to store values that don't change, such as configuration options or static data that you want to reference in your code.

Here's an example of how you might use a constant in a React component:

In this example, the constant API_ENDPOINT is used to store the URL of an API endpoint. This constant is then used in the fetch call to retrieve data from the API.

It's important to note that constants in React are only available within the scope in which they are defined. In the example above, the MY_CONSTANT constant would only be available within the MyComponent function. If you want to use a constant in multiple components, you would need to define it in a separate file and import it into the components that need it.

Overall, constants can be a useful tool for organizing and managing your code in React. They can help you avoid hardcoding values and make your code more maintainable and reusable.

November 06, 2022

November 03, 2022

Get the Reddit app

A community for discussing anything related to the React UI framework and its ecosystem. Join the Reactiflux Discord (reactiflux.com) for additional React discussion and help.

How come, we can modify the const variable in react but not in vanilla js ?

We use const variables in react and can easily modify the value. While same thing in vanilla js throws error. Why ?

Edit: I'm talking about useState hook. sorry, if am not even asking the right question.

By continuing, you agree to our User Agreement and acknowledge that you understand the Privacy Policy .

Enter the 6-digit code from your authenticator app

You’ve set up two-factor authentication for this account.

Enter a 6-digit backup code

Create your username and password.

Reddit is anonymous, so your username is what you’ll go by here. Choose wisely—because once you get a name, you can’t change it.

Reset your password

Enter your email address or username and we’ll send you a link to reset your password

Check your inbox

An email with a link to reset your password was sent to the email address associated with your account

Choose a Reddit account to continue

IMAGES

  1. Using constant object values into React Component in React JS

    react js assignment to constant variable

  2. How to declare const array in React js?

    react js assignment to constant variable

  3. React JS Method Call , Use Of Constant and Constructor in a Component

    react js assignment to constant variable

  4. 41 How To Declare A Constant In Javascript

    react js assignment to constant variable

  5. JavaScript Features You Need to Know to Master React

    react js assignment to constant variable

  6. React Native

    react js assignment to constant variable

COMMENTS

  1. javascript - Error "Assignment to constant variable" in ...

    I have noticed I am creating an empty object called "resObj", then trying to assign a value to it. I have tried changing the CONST to LET, but I get an error saying: "resObj is not defined". Here is my front end code: import React, { useState } from "react"; const [loading, setLoading] = useState(false);

  2. type error = assignment to constant variable react.js

    If you want to update your state (that is an array) in react hooks, you should try like this : const new_todo = (input) => set_todos(oldState => [...oldState,input]) with this code, you will not see any error but I have some offer for your code that make it better:

  3. TypeError: Assignment to Constant Variable in JavaScript

    The "Assignment to constant variable" error occurs when trying to reassign or redeclare a variable declared using the `const` keyword.

  4. TypeError: invalid assignment to const "x" - JavaScript | MDN

    The JavaScript exception "invalid assignment to const" occurs when it was attempted to alter a constant value. JavaScript const declarations can't be re-assigned or redeclared.

  5. ES6 Variables in React.js - Medium

    c = 6; // Error: Assignment to constant variable. Using ES6 Variables in React.js. In React.js, you’ll typically use const to declare your components, since they should not be reassigned....

  6. TypeError: Assignment to constant variable. #16211 - GitHub

    What I think you're trying to is something like this: const something = 1; something = 2; Even though the path implies that the error happens in react, I think the error happens in your code, but it's difficult to tell from a single line.

  7. TypeError: Assignment to constant variable when using React ...

    Learn about the common error 'TypeError: Assignment to constant variable' that occurs when using the React useState hook in JavaScript. Understand the cause of the error and how to resolve it effectively.

  8. React ES6 Variables - W3Schools

    Variables. Before ES6 there was only one way of defining your variables: with the var keyword. If you did not define them, they would be assigned to the global object. Unless you were in strict mode, then you would get an error if your variables were undefined. Now, with ES6, there are three ways of defining your variables: var, let, and const.

  9. How to define constants in React? - JS.ORG

    In React, you can define constants using the const keyword. For example: const MY_CONSTANT = "hello"; This creates a constant named MY_CONSTANT with the value "hello". Constants are like variables, except that their value cannot be changed once they are assigned.

  10. variable in react but not ...">How come, we can modify the const variable in react but not ...

    const is all about forbidding reassignment of a variable identifier. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).