React JS Forms | Controlled Inputs | Learn ReactJS

Ғылым және технология

Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGrayWebDevRoadmap
React JS Forms utilize controlled inputs linked to React state which is a different approach than we learn with HTML and Javascript. Linking React controlled form inputs to React state create a single source of truth for our controlled components.
🚩 Subscribe ➜ bit.ly/3nGHmNn
🚀 This lesson is part of a Learn React tutorial series playlist:
• React Tutorials
🔗 Source Code for this tutorial: github.com/gitdagray/react_co...
React JS Forms | Controlled Inputs | Learn ReactJS
(00:00) Intro
(00:05) Set up and clean up
(03:06) Creating a Form Component
(07:44) Adding CSS Styles to the form
(09:24) Sending props to the form component
(11:47) Making a controlled input component
(13:58) The handleSubmit function
(17:52) The addItem function
(21:04) The setAndSaveItems function - D.R.Y. (don't repeat yourself)
(22:15) Adding new items
(23:17) Loading state from localStorage
(24:58) Search Functionality
(25:40) Building the search input component
(27:50) Props for the search input component
(29:03) Completing the controlled search input component
(31:34) Adding search functionality with filter()
(33:58) Review of Controlled Form Input Components
(34:32) The useRef hook
🔗 ES7 React JS Snippets Extension for VS Code:
marketplace.visualstudio.com/...
🔗 React Dev Tools Extension for Chrome:
chrome.google.com/webstore/de...
🔗 Styled Components: styled-components.com/
📚 References:
ReactJS Official site: reactjs.org/
React Wikipedia: en.wikipedia.org/wiki/React_(...)
React Jobs: www.ziprecruiter.com/candidat...
✅ Follow Me:
Twitter: / yesdavidgray
LinkedIn: / davidagray
Blog: yesdavidgray.com
Reddit: / daveoneleven
Was this tutorial about Controlled Form Inputs in React JS helpful? If so, please share. Let me know your thoughts in the comments.
#react #controlled #inputs

Пікірлер: 116

  • @DaveGrayTeachesCode
    @DaveGrayTeachesCode3 жыл бұрын

    When React form inputs are linked to state, they are called Controlled Components. This linking of input to state is different than the way traditional HTML forms handle submission. Understanding this linkage is critical for making your React apps interactive. If you are just starting out with Javascript, I suggest starting with full 8 hour Javascript tutorial here: kzread.info/dash/bejne/d5p1zpubp928is4.html

  • @wahidurrahman77

    @wahidurrahman77

    3 жыл бұрын

    Thanks

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    3 жыл бұрын

    @@wahidurrahman77 you're welcome! 🙏

  • @nikoryu-lungma

    @nikoryu-lungma

    Жыл бұрын

    Hi, Mr. Dave. I have been learning ReactJS from your videos recently. However, I had an error when I reached chapter 9. I kept getting these errors "ncaught TypeError: Cannot read properties of undefined (reading 'length') at Content (Content.jsx:6:20)" I don't really understand what this means. Can you please explain to me? I have tried stack overflow and the other google site, but it did not help much

  • @toonice555
    @toonice55511 ай бұрын

    Very clean way to filter! state stays the same and you just filter the results you pass to the component. very nice! i always created a filtered state but this is so much easier and reduces the need for extra states for no reason.

  • @lakshmidesineedi7421
    @lakshmidesineedi74212 жыл бұрын

    Fantastic teacher !!! Thanks Dave i learned a lot from this series.

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    2 жыл бұрын

    Great to hear! 💯🙏

  • @akanj2309
    @akanj23093 жыл бұрын

    Thank you for this series, Keep up the great work!

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    3 жыл бұрын

    Thank you 🙏💯🚀

  • @sakibcoder
    @sakibcoder Жыл бұрын

    I'm following your tutorial. I don't know how much I will get but your tutorial seems easy to me. Thanks

  • @eeedit8870
    @eeedit887010 ай бұрын

    Kudos. Great materials for learning React!

  • @khaledbenshible2657
    @khaledbenshible2657 Жыл бұрын

    Fantastic, thank you very very....much. Please don't stop making React.js videos

  • @ZeeshanMRaje
    @ZeeshanMRaje8 ай бұрын

    I must say this guy is legend , Love & respect from India (Pune)

  • @toonice555
    @toonice55511 ай бұрын

    So many great details

  • @noir4356
    @noir4356 Жыл бұрын

    Your tutorials are probably the best out there :) Subbed.

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    Glad you like them!

  • @fazzyakamello
    @fazzyakamello3 жыл бұрын

    Amazing tuts as always Dave!

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    3 жыл бұрын

    Thank you fazzy! 🙏

  • @kannder83
    @kannder832 жыл бұрын

    Thank you for your course. I have really learned a lot of things.

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    2 жыл бұрын

    Glad it was helpful! 🚀

  • @viditgoel2909
    @viditgoel290910 ай бұрын

    Great Tutorial Sir

  • @Ujedkemal
    @Ujedkemal Жыл бұрын

    Hi Dave, i just learned a lot form your video. i supposed to learn from your channel since a long time ago . I regret so much to just find your channel a few days ago. thanks a lot dave. big regards from Indonesia

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    Thank you and hello to Indonesia! 👋

  • @dusanvulic7275
    @dusanvulic7275 Жыл бұрын

    Awesome explained search functionality ! Thank you very much !

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    You're welcome!

  • @CODEABC
    @CODEABC3 жыл бұрын

    I love your teaching method..please make a play list like this one with node. Then make more and more project with mern stack

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    3 жыл бұрын

    Thank you for the kind words. Those are both great suggestions!

  • @yajur.bhrdwj
    @yajur.bhrdwj9 ай бұрын

    hey dave since i did not had any data in the local storage, i added this statement in app.js :- const [items, setItems] = useState(JSON.parse(localStorage.getItem('shoppinglist')) || [ ] ); But how should i add data to the local storage before. how did you add data milk and bread before into the local storage?

  • @fernandosalas4885
    @fernandosalas48852 жыл бұрын

    Please don't stop making React.js videos. You are the best!

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    2 жыл бұрын

    Thank you!

  • @aman7555
    @aman75552 жыл бұрын

    Excellent as always!

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    2 жыл бұрын

    Thank you, Aman! 🙏

  • @Netpilation
    @Netpilation Жыл бұрын

    Dave i did not really get it there when check for the blank value and prevent it from getting submitted . cause you have already set the value of new item to an empty string and empty sring returns a truthy value

  • @abdulrahmanagboolaosho3582
    @abdulrahmanagboolaosho3582 Жыл бұрын

    another excellent tutorial, thanks man

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    Welcome! 🙏🙏

  • @codingispower1816
    @codingispower18168 ай бұрын

    At what point does the parent component (in this case App.jsx) become too large from lifting all the state up? How can this be optimized or broken out efficienty?

  • @vishalkashyap8480
    @vishalkashyap84809 ай бұрын

    Here in the form input element we have provided 'required' as an attribute then why the need of if (! newItem ) return ;

  • @tomaszklekner9879
    @tomaszklekner9879 Жыл бұрын

    Amazing content!!!

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    Thanks!!

  • @4rmStd
    @4rmStd7 ай бұрын

    Thank you for lesson! But i have one question Why did you write (item.item) instead of one item? Isn't the first item already the string itself or have I misunderstood something?

  • @oussamabouallati
    @oussamabouallati Жыл бұрын

    Thank you sir!

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    You are welcome!

  • @omaralazzawi5305
    @omaralazzawi53052 жыл бұрын

    thanks a lot Dave

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    2 жыл бұрын

    You're welcome Omar! 🙏

  • @ahmad-murery
    @ahmad-murery3 жыл бұрын

    Very neat project, One useful functionality to have here is to sort the list items by the checked field so that all checked items moved to the bottom, but we need then to change the id generator function to lookup the list for the max id instead of directly using the last item id + 1, maybe using Array.reduce function, Idea/suggestion, maybe after implementing the server-side code we can take the project to just another next level by modifying currently implemented local storage to handle offline usage, I think a simplified syncing mechanism can be create to push offline marked items to the server, Thanks Dave,

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    3 жыл бұрын

    Great suggestions Ahmad. 💯 Definitely leveling it up from beginner status. I will be mocking data requests soon. 🚀

  • @ahmad-murery

    @ahmad-murery

    3 жыл бұрын

    ​@@DaveGrayTeachesCode Great, I think the syncing concept itself would be very helpful

  • @neo90sr
    @neo90sr2 жыл бұрын

    Fantastic, thank you for these videos! You should do a react course on udemy

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    2 жыл бұрын

    Thank you for your encouragement! 🙏

  • @subliminakeys1674
    @subliminakeys1674 Жыл бұрын

    Huge fan of your videos! Very descriptive and engaging. I especially like how you constantly say the shortcut keys you are using, helps drill those into my head for memory. I want to note though, I ran into an error. You dont address what will happen if local storage is empty and you try to getItem. I got a black screen when i cleared my storage. I added an if statement to check if local storage returns null. If null then I set item to json stringify an empty array. I dont know if its best practice, but it solved my issue. edit- I seen another comment that addressed this and their solution was better. They just used '|| []' after the localStorage.getItem statement and its much cleaner than another if statement like i had

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    Yes, keep going and I address this in one of the next lessons. Start the useState() hook with an empty array inside. 💯

  • @subliminakeys1674

    @subliminakeys1674

    Жыл бұрын

    @@DaveGrayTeachesCode sounds good thanks for the content! Side question which I can't wrap my brain around and I know it's probably tough without my code but... The input for adding a new item is not resetting the text field to empty when I click the button like yours does. Everything else is functioning and it's changing the inputs new state value to ' ' in the console log I tried , but it's not actually removing the text from the input box, I have to delete it manually. Is there something I could investigate that may be stopping that from working since it is actually changing the value to ' ' but not changing the inputs text?

  • @TeslavsEdison1

    @TeslavsEdison1

    Жыл бұрын

    I also had the bright idea of clearing local storage to test this lol. Will keep going to see Dave's solution in the next lesson but in case anyone else is a bit stuck I found a simply ternary to fix it in the meantime ``` const localItems = JSON.parse(localStorage.getItem('shoppinglist')) const [items, setItems] = useState(localItems ? localItems : []) ```

  • @subliminakeys1674

    @subliminakeys1674

    Жыл бұрын

    @@TeslavsEdison1 yes this works good. You can also use || to define a default if the variable doesn't exist. const Storage = localStorageVariable || [] If localStorageVariable is falsy it will return [] instead.

  • @min0234
    @min0234 Жыл бұрын

    thanks again for the tutorial! Quick question, I noticed that you used camel case in the index.css, and I wanted to know if that's okay to do that. VS code gave me a little message to use kebab-case instead of camel case, but I also get that we used camel case in the jsx file. Is it safe to use camel clase in CSS file? or naming in camel case in jsx file?

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    Good question! You can use camelCase in CSS but I do think the kebab-case you mentioned is usually more desirable and used more often.

  • @jiweihe3413
    @jiweihe34132 жыл бұрын

    Thanks for another great video. At the end of the video, is ‘inputref.current’ a current state? Does it always pointing to the input element? Trying to understand what inputref.current.focus() is doing.

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    2 жыл бұрын

    It sets the focus on the input when the component loads. For more on the useRef hook, here is a dedicated video: kzread.info/dash/bejne/pWqJo9d_qq-ZYJs.html

  • @midouwebdev2224
    @midouwebdev22243 жыл бұрын

    Thanks sir

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    3 жыл бұрын

    You're welcome! 🙏

  • @oncoding4520
    @oncoding4520 Жыл бұрын

    As I say I will comment on each of your video in order to help you out :) Just a question, after I finish this course which course will be recommended by you to take bcs for example you have a lot of react videos also. I just saw 1min of React hooks and it seems that they are some part of other react videos (maybe this playlist !) like I dont know. After I finish all the 52 videos here should I goo to authentication ?

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    After learning React, I recommend Node.js if you haven't learned it yet. This will allow you to create full stack applications.

  • @oncoding4520

    @oncoding4520

    Жыл бұрын

    @@DaveGrayTeachesCode I will :) thank you Dave

  • @oncoding4520

    @oncoding4520

    Жыл бұрын

    A little help pls: I have here so far, even did the challenge but I just open my console and clear all the localStorage (just to see) and now everything doesnt work. I even just clone your code and it gives me the same error "TypeError: Cannot read properties of null (reading 'filter')'. I think it has to do bcs I clear the localStorage so the filter method dont work. My code and your repo are the same, and it gives me this kind of error!

  • @oncoding4520

    @oncoding4520

    Жыл бұрын

    Got it, from the useEffect video. Somehow I sense it that we are missing data, since we clear the localStorage it means that we dont have anything to display to user

  • @tonysingh5334
    @tonysingh5334 Жыл бұрын

    at 20:06 why are you only defining values for the object and not the keys ?

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    Good question - this applies to Javascript and not just React - if the object property and the variable have the same name, you can just say item instead of saying item: item.

  • @googleboughtmee
    @googleboughtmee2 жыл бұрын

    Do we still need those semi-colons on the end of lines? Half the lines have them and half don't

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    2 жыл бұрын

    Great question - you usually don't need them. I'm trying to break myself of habitually using them. I learned with them, so I have to think about it to avoid them.

  • @googleboughtmee

    @googleboughtmee

    2 жыл бұрын

    @@DaveGrayTeachesCode Thanks. Yeah I can understand that. Back when I learned JS, I knew they weren't always needed but was told to *always* use them anyway. Now I'm watching React tuts and everything in JS has changed so much, and it was seeming like they've fallen out of favour for good now. That's fine, it just still feels strange to leave them off 🙂

  • @Xylasider
    @Xylasider2 жыл бұрын

    Question. As long as the array isn't empty, won't items.length always be the same as the last id? Why will items.length + 1 not work?

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    2 жыл бұрын

    Good question! You need to refer to the length value - 1 to get the actual needed value from the array. This is because the index of the array starts at zero but the length property starts at 1. Notice items[items.length - 1].id is getting the id value. Experiment with it and you will see what I mean. Great, thoughtful question - good work!

  • @Xylasider

    @Xylasider

    2 жыл бұрын

    @@DaveGrayTeachesCode I think I figured out the answer to my question. And it's because of deleting items. If you don't delete anything, items.length will always be the same value as the id of the last item. But if you've deleted items, it will throw off that synergy and could cause you to create two entries with the same ID if you only use length.

  • @nikoryu-lungma

    @nikoryu-lungma

    Жыл бұрын

    I had an error when I reached chapter 9. I kept getting these errors "ncaught TypeError: Cannot read properties of undefined (reading 'length') at Content (Content.jsx:6:20)" I have tried stack overflow and the other google site, but it did not help much

  • @SeekerofUniverse33
    @SeekerofUniverse33 Жыл бұрын

    I have hardtimes understand login behind this line could you pls explain how how pass search and getting result here?? {items.filter(item=>((item.item).toLowerCase()).includes(search.toLowerCase()))}

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    To understand this line of code, we need to go back to JavaScript fundamentals - both string methods - toLowerCase() - and higher order functions - Array.filter() - I think toLowerCase() explains itself, but here is my tutorial on higher order functions like filter: kzread.info/dash/bejne/aXaZtpilo9jKfJc.html

  • @tuanphamvan655
    @tuanphamvan6552 жыл бұрын

    Good

  • @kiranrai5014
    @kiranrai5014 Жыл бұрын

    if we delete all the items and close the browser, and again restart the server, it displays an error saying items.length is invalid as items is null in the footer and content section as both reads .length property for the expression. can you help me to solve this issue.

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    Several comments here discussing this. If you keep going, I talk about it in the next lessons. You need to put an empty array in your useState hook: useState([ ])

  • @kiranrai5014

    @kiranrai5014

    Жыл бұрын

    @@DaveGrayTeachesCode if we use useState hook and initialize an empty array then if we refresh the browser then all the items will be deleted as the list will be empty and there will be no use of using localStrorage. I have a question why the localstorage is showing null when we empty all the elements and refresh the browser it should show and empty array as we have not explicitly remove the array from the localstorage. can you please explain me this?

  • @kiranrai5014

    @kiranrai5014

    Жыл бұрын

    @@DaveGrayTeachesCode we can one thing as of my knowledge we can use a ternary operator in the useState hook and check if localStorage is empty or not if not then we can retrieve the data from it, or if it's empty then we can initialize and empty array.

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    Hi Kiran - I didn't provide my full explanation here - expecting you to go forward in the lessons for this playlist as suggested. Yes, only providing an empty array will not load the items - I use the OR operator that looks like this: || ..please continue forward in the playlist.

  • @nikoryu-lungma

    @nikoryu-lungma

    Жыл бұрын

    @@kiranrai5014 I had the same problem when I reached chapter 9. I kept getting these errors "ncaught TypeError: Cannot read properties of undefined (reading 'length') at Content (Content.jsx:6:20)" Can you please explain to me? I have tried stack overflow and the other google site, but it did not help much Like, it worked at first, but then, when I re-run it the second time, the errors keep showing up.

  • @jamshidtashkent1976
    @jamshidtashkent1976 Жыл бұрын

    Could you please explain to me what this code means? I got the whole idea, but this part is difficult for me to understand : { ...item, checked: !item.checked }. If item.id === id true, {...item ( spread operator), checked ... const handleCheck = (id) => { const listItems = items.map((item) => item.id === id ? { ...item, checked: !item.checked } : item); }

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    Sure! When we create a new object, we spread in the properties and associated values of the previous object. Then we add a comma and overwrite the property we want to update with a new value. In this case, item.checked is boolean so !item.checked is the opposite of the previous value.

  • @jamshidtashkent1976

    @jamshidtashkent1976

    Жыл бұрын

    @@DaveGrayTeachesCode thank you.

  • @salehm5413
    @salehm54132 жыл бұрын

    Hi Master Dave i want to ask you about How I can start my own project i was watched your toutirul but i can not do any think with my own self. how i can fixed this problem and thancks for all this amazing content and how you are learned all this stuff with your own self ❤ have a good day .

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    2 жыл бұрын

    Good question - you are asking about things that are tough to teach: problem solving and creativity. The best way for you to learn these things is to start building a project of your own without following a step-by-step tutorial. It is the same reason I put a code challenge or two in this course. You have to creatively think about how to apply what you have learned and solve the problem on your own. Challenge yourself to build a recipe app, contacts list, or other variation of a todo list. See if you can put together what you learn from this course to build your own project. 💯🚀

  • @salehm5413

    @salehm5413

    2 жыл бұрын

    @@DaveGrayTeachesCode Thank you Mr. Dave, I think my real problem is that I don't challenge myself, I just depend on others. I hope you have a good day ❤👍

  • @harshjayantdiwase7160
    @harshjayantdiwase7160 Жыл бұрын

    Cannot read properties of null (reading 'filter') TypeError: Cannot read properties of null (reading 'filter') this error is comiing

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    If using the useState hook, you may want an empty array in there for your starting state. This may also be addressed in the next video if you keep going.

  • @abdulrahmanagboolaosho3582
    @abdulrahmanagboolaosho3582 Жыл бұрын

    At first I thought react wasn't meant for me, but now I have become more confident

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    Great work!

  • @jobisintheair-bv7jm
    @jobisintheair-bv7jm8 ай бұрын

    I like the video but I feel there is a huge level increase from the previous ones. Thanks anyway. Good stuff.

  • @alisaleem2381
    @alisaleem23812 жыл бұрын

    Hi sorry if I sound rude but I think thumbnail of actual preview might make more people to click on your vids. BTW your tutorials are to the point and soo good for a beginner. 👌 You are underrated.

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    2 жыл бұрын

    Thanks for the suggestion and the kind words 🙏

  • @nikoryu-lungma

    @nikoryu-lungma

    Жыл бұрын

    I had an error when I reached chapter 9. I kept getting these errors "ncaught TypeError: Cannot read properties of undefined (reading 'length') at Content (Content.jsx:6:20)" Can you please explain to me? I have tried stack overflow and the other google site, but it did not help much

  • @SeekerofUniverse33
    @SeekerofUniverse332 жыл бұрын

    const handleSubmit = (e)=>{ e.preventDefault(); if(!newItem) return; -- addItem(newItem); setNewItem('');

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    2 жыл бұрын

    Hi Lavesh, I'd need to go back and review the tutorial and code to know specifics, but the first line you are asking about checks to see if a newItem exists. If not, it is just an early return to exit the function. The 2nd line you are asking about looks like it sets the newItem state back to any empty string after adding the newItem.

  • @SeekerofUniverse33

    @SeekerofUniverse33

    2 жыл бұрын

    @@DaveGrayTeachesCode Thanks dave got it

  • @TravinskiyVladislav
    @TravinskiyVladislav Жыл бұрын

    Comment for up

  • @harag9
    @harag9 Жыл бұрын

    LOL I just commented on previous lesson about the key attribute on the tag then started watching this one... and the first thing you do... removes the attribute :). In your CSS at the start you labelled it "addForm" & "searchForm" -- however isn't css convention all lowercase with dashes e.g. "add-form", or is this a css/react convention ? I've always done it all lower with dashes. Great episode, many thanks. Looking for to the rest in the play list. :)

  • @nithinjoji7487
    @nithinjoji7487 Жыл бұрын

    hi dave.. Objects are not valid as a React child (found: object with keys {id, checked, item}). If you meant to render a collection of children, use an array instead.

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    I am not sure where you are getting this error (share a timestamp?), but I did not get this error in my tutorial.

  • @WrathNBrimstone
    @WrathNBrimstone2 жыл бұрын

    you've got way too many js items trying to teach inherited props and mutliple modular calls this is very bad for learning

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    2 жыл бұрын

    I disagree, but I don't expect everyone to like the way I teach. This course has a beginners approach and the code is continuously refactored as the tutorials progress. I do appreciate constructive feedback.

  • @lakshmidesineedi7421
    @lakshmidesineedi74212 жыл бұрын

    Hi Dave const [items, setItems] = useState(JSON.parse(localStorage.getItem('shoppinglist'))); using this statement i tried to get the data from local storage and the output was complete blank page. please help.

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    2 жыл бұрын

    Refer to my source code at the course resources link in the description. Compare to yours to find the differences.

  • @yajur.bhrdwj

    @yajur.bhrdwj

    9 ай бұрын

    const [items, setItems] = useState(JSON.parse(localStorage.getItem('shoppinglist')) || [ ] ); use this. i had the same error, then got to know that the local storage has no data before.

  • @soniablanche5672
    @soniablanche56723 жыл бұрын

    I've noticed a bug when setting the initial data. The very first time you launch the application (or when you wipe the local storage), localStorage.getItem('shoppinglist') returns null, and JSON.parse(null) returns null, but our application expects an array. I would set an empty array as a default value for this particular case. JSON.parse(localStorage.getItem('shoppinglist')) || [];

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    3 жыл бұрын

    Good catch Sonia! Yes, a new user that did not have the localStorage "shoppinglist" already would encounter this. I cover this in the useEffect tutorial coming up, too. And great job! I applied the same short circuit || in my tutorial at load as you are recommending here.

  • @subliminakeys1674

    @subliminakeys1674

    Жыл бұрын

    I just noticed this as well and made a comment I will be deleting after seeing yours. I appreciate this advice, my way of fixing it worked but was way more complex than it needed to be because I wrote an entire if statement to handle this instead of using ||

  • @najmantube
    @najmantube4 ай бұрын

    If you get the error: "Uncaught TypeError: Cannot read properties of null (reading 'length')", after changing the hardcoded object to: const [items, setItems] = useState(JSON.parse(localStorage.getItem('shoppinglist'))); rewrite the code as follows: const [items, setItems] = useState(JSON.parse(localStorage.getItem("shoppinglist")) || []); Now, if JSON.parse(localStorage.getItem("shoppinglist")) returns null, the default value of an empty array will be used.

  • @ruslangilyazov7733
    @ruslangilyazov77332 ай бұрын

  • @oussamabouallati
    @oussamabouallati Жыл бұрын

    Thank you sir!

  • @DaveGrayTeachesCode

    @DaveGrayTeachesCode

    Жыл бұрын

    You are welcome!

Келесі