I have a react native app and i'm trying to update a Date in a custom context.
ThemeContext
export const ThemeContext = React.createContext({
theme: 'dark',
toggleTheme: () => { },
date: new Date(),
setDate: (date: Date) => { }
});
Basic context with the date and the function to update it
App.tsx
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
theme: 'dark',
date: new Date()
};
}
render() {
const { theme, date } = this.state;
const currentTheme = themes[theme];
const toggleTheme = () => {
const nextTheme = theme === 'light' ? 'dark' : 'light';
this.setState({ theme: nextTheme });
};
const setDate = (date: Date) => {
// ERROR is raised HERE
this.setState({date: date});
}
return (
<>
<IconRegistry icons={EvaIconsPack} />
<ThemeContext.Provider value={{ theme, toggleTheme, date, setDate }}>
...
</ThemeContext.Provider>
</>
);
}
}
I simply hava a state with a Date and create a setDate function. I wrapped my app into the context provider.
Picker
class PickerContent extends React.Component<{}, ContentState> {
static contextType = ThemeContext;
constructor(props: {} | Readonly<{}>) {
super(props);
let currentMode = 'date';
let show = false;
if (Platform.OS === 'ios') {
currentMode = 'datetime';
show = true;
}
this.state = {
date: new Date(),
mode: currentMode,
show: show
};
}
setMode(currentMode: string) {
this.setState({ mode: currentMode, show: true });
};
onChange(_event: any, selectedDate: Date) {
const currentDate = selectedDate || this.state.date;
// I update the context here
this.context.setDate(currentDate);
this.setState({date: currentDate, show: Platform.OS === 'ios'})
}
render() {
const {show, date, mode } = this.state;
const color = 'dark';
return (
<>
...
{show && <DateTimePicker
...
onChange={(event, selectedDate) => this.onChange(event, selectedDate)}>
</DateTimePicker>}</>
)
}
}
I use the lib 'DateTimePicker' to choose a date and bind the onChange to update the context. This picker is on a modal.
So the warning appears when the onChange
function of DateTimePicker is trigger. The error is on the setState
of App.tsx
(in setDate)
Warning: Cannot update during an existing state transition (such as within 'render'). Render methods should be a pure function of props and state.
Would you know how to correct this error?
EDIT :
I was using a Modal component from the UI Kitten library. I switch to the react native Modal and the error is gone. It seems that the error comes from the Library. SORRY
thank you in advance for your help, Sylvain
I edited my question. The error finally seems to come from the library used (ui kitten).