Search code examples
reactjslodash

lodash solution for input value ={}


I have a form with some input fields, and I need to get a JSON from server, then take input default values form that JSON object, but sometimes the object might be empty due to network problems, and at such times the I get error that the value can not be null, I need a way to handle that with Lodash, can anybody please help me? and please tell me how do I pass it to value={}

the example of not using Lodash is below, I wanna get rid of all &&s in my code

<Input value={userProfile && userProfile.result.job} onChange={() => setJob(...userProfile.result.job)}  />

Solution

  • Vanilla JS has conditional chaining ?. syntax:

    const userProfile = null
    
    console.log(userProfile?.result?.job)

    If conditional chaining cannot be supported, you can use lodash's _.get():

    const userProfile = null
    
    console.log(_.get(userProfile, 'result.job'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>