Home > Software engineering >  Pass a value to a react hook
Pass a value to a react hook

Time:12-08

Got a Component that is using a separate hook created but I'm unable to pass any value to that hook which I require in my use case.

const onEdit = (index: number) => useMediaLinkImage(img => {

        setNodeImages(imgData => {

            imgData[index] = {
                ...imgData[index],
                image: {
                    ...imgData[index].image,
                    image: img
                }
            }


            return imgData
        })
    })

return --------------

{
            nodeImages.map(({ image, mode }, index) => <Image
                    key={index}
                    mode={mode}
                    image={image}
                    onEmpty={onEmpty}
                    onChange={onValueChange}
                    onSubmit={onSubmit}
                    onToggle={onToggle}
                    onEdit={() => onEdit(index)}
                    onAdd={addImage}
                />)
            }

unable to get use it as a function to get the index for the onEdit throws error

React Hook "useMediaLinkImage" is called in function "onEdit" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use".

CodePudding user response:

It expects that onEdit is a component that should return a JSX element or null or undefined but you return useMediaLinkImage hook, because with this arrow function syntax (index: number) => useMediaLinkImage it's a shortcut for

(index: number) => {
  return useMediaLinkImage((img) => {
     // code ..
  })
}

You just need to use brackets without return.

const onEdit = (index: number) => {
   useMediaLinkImage(img => {

        setNodeImages(imgData => {

            imgData[index] = {
                ...imgData[index],
                image: {
                    ...imgData[index].image,
                    image: img
                }
            }


            return imgData
        })
    })
}

CodePudding user response:

You can just call hooks inside other hooks, or inside the main body of a React component.

In you case, you have to return the function you want to call from the hook itself:

function useMediaLinkImage(...) {
    // set your custom state here
    function update(index, ...) {
        ...
    }
    return {
        ... // return state variables from here if needed
        update
    };
}

Then in your component:

const { update } = useMediaLinkImage(...);

const onEdit = (index: number) => {
  update(index, ...);
}
  • Related