Synchro
Synchro

Reputation: 1269

React How to pass hook value to CreateContext

I have a SideBarBlurChange component, I need to pass a value called values inside the BlurChangeValue array, which is inside CreateContext.

On the Internet I did not find a suitable example, I hope that it is possible to reolize, because so far I have no other options for reolizing. I want to show a screenshot of what I want to do to make it clearer for you

enter image description here

export const BlurContext = createContext({
    BlurChangeValue: [],
});

export default function SideBarBlurChange(props) {

    const ls = parseInt(window.localStorage.getItem('values'));
    const [values, SetValues] = useState(ls ? [ls] : [20]);

    const SaveChanges = () => {
        localStorage.setItem('values', values);
    }

    return (
        <>
            <BlurContext.Provider values={values}>
                // jsx
            </BlurContext.Provider>
        </>
    );
}

Upvotes: 0

Views: 273

Answers (1)

欧阳斌
欧阳斌

Reputation: 2351

A lot of mistakes

1. const ls = parseInt(window.localStorage.getItem('values')); seem localStorage.values is number, but localStorage.setItem('values', values); set as array
2. createContext({ BlurChangeValue: [], }); create a Object context with property BlurChangeValue, but <BlurContext.Provider value={values}> provide array values


const [values, setValues] = useState(()=> JSON.parse(localStorage.getItem('values') || '[20]'));
const saveValues = ()=> {
    localStorage.setItem('values', JSON.stringify(newValues));
}
return (
<BlurContext.Provider values={{BlurChangeValue: values}} >
)
;

Upvotes: 2

Related Questions