I'm working with the React Context API, and I've got the following as an example
import React, { createContext, useState } from 'react';
const FooContext = createContext({
bar: false,
toggleBar: () => {}
});
export const FooContextConsumer = FooContext.Consumer;
export const FooContextProvider = ({ children }) => {
const [bar, setBar] = useState(false);
const toggleBar = () => setBar(!bar);
return (
<FooContext.Provider value={{ bar, toggleBar }}>
{children}
</FooContext.Provider>
)
};
export default FooContext;
Now, there's a lot of exports going on here. I know that the createContext functions has { Provider, Consumer } destructure properties available. Is there a way I can use that to compact this code? I've got something like this in mind but that isn't valid syntax unfortunately..
import React, { createContext, useState } from 'react';
export default ({ Provider, Consumer }) = createContext({
bar: false,
toggleBar: () => {}
});
export const FooContextConsumer = Consumer;
export const FooContextProvider = ({ children }) => {
const [bar, setBar] = useState(false);
const toggleBar = () => setBar(!bar);
return (
<Provider value={{ bar, toggleBar }}>
{children}
</Provider>
)
};
So, I want to export createContext function as the default, while using the Provider and Consumer properties of that function within the same file. Is this possible?
Of course I can do it with a const and an export default but I was wondering if this is possible as a one-liner.