Javascript

How to fix Uncaught TypeError: Cannot assign to read only property ‘0’ of object occurring in JavaScript?

Hello,

This type error mostly get in scenario when you try to sort the readyonly data array.

For me this was occoured when I tried to sort the direct result from my GraphQL query response data like below:

const sortedData = data.bhangarwalas.sort((a, b) => a?.firstname > b?.firstname ? 1 : -1);

In above, data.bhangarwalas is graphql query response results which is readonly in nature as response.

To fix this issue the solution is quick fix for which I have too google to know the result!

Error Screenshot Uncaught TypeError: Cannot assign to read only property ‘0’ of object ‘[object Array]’

Here is the quick solution:

const sortedData = [...data.bhangarwalas];
      sortedData.sort((a, b) => a?.firstname > b?.firstname ? 1 : -1);

In code above, We need to clone or you in other words, copying the “data.bhangarwalas” into new array variable and then over that variable, we need to perform sorting operation, which results us right response.

Hope this help you to solve the quick error or to know what scenario this type of error is generated.

Thanks for reading.

Happy learning!

admin

Recent Posts

What I Learned After Taking Break from Instagram for 30 Days

Break! I didn’t plan it. One day I just didn’t feel like opening Instagram—and then…

2 days ago

5 AI Tools That Actually Save You Time (And Aren’t Scary)

AI tools Let’s be real—AI sounds like either a robot apocalypse or something only tech…

2 days ago

Summer Learning Ideas

Summer vacation is a great time for kids to explore, have fun, and learn new…

5 days ago

Understanding How ChatGPT Works (ML/AI learning path)

Goal: Understand transformers, large language models, and the architecture behind ChatGPT. Tutorial Suggestions: ✅ “Transformers…

5 days ago

Using ChatGPT API (for developers)

Goal: Build apps or tools with ChatGPT or GPT-4 API. Tutorial Suggestions: ✅ OpenAI API…

5 days ago

Using ChatGPT Effectively (for general users or productivity)

Goal: Learn how to prompt better, write content, brainstorm, code, etc. Tutorial Suggestions: ✅ OpenAI's…

5 days ago