2

To clearify I'm pretty newbie with the concept of react-redux. I try to dispatch an async action in the presentational comp. but this does not seem to work out.

Container Component

const store = configureStore();

const Root: React.FC = () => (
    <Provider store={store}>
        <App />
    </Provider>
);

render(<Root/>, document.getElementById('root'));

Presentational Component

interface AppProps {
    system: SystemState,
    updateSession: typeof updateSession,
    getLanguageThunk: any
}

const App: React.FC<AppProps> = ({system, updateSession, getLanguageThunk}) => {
    useEffect(() => {
        getLanguageThunk().then((res: any) => {
            console.log(res);
            i18n.init().then(
                () => i18n.changeLanguage(res.language));
       });
    }, []
);

    return (
            <div>
                <div className="app">
                    <TabBar/>
                </div>
            </div>
    );
};

const mapStateToProps = (state: AppState) => ({
    system: state.system
});

export default connect(mapStateToProps, { updateSession, getLanguageThunk })(App);

But the console everytime logs undefined. So I am doint something wrong here. Maybe some of u can help me out on here.

Redux middleware

export const getLanguageThunk = (): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
    const language = await getLanguage();
    dispatch(
        updateSession({
            disableSwipe: false,
            language
        })
    )
};

async function getLanguage() {
    try {
        const response = await fetch('http://localhost:3000/language');
        return response.json();
    } catch {
        return { language: 'en_GB' }
    }
}

1 Answer 1

2

You need to return the language from getLanguageThunk, to be able to use it from promise in the useEffect method

export const getLanguageThunk = (): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
    const language = await getLanguage();
    dispatch(
        updateSession({
            disableSwipe: false,
            language
        })
    )
    return language;
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.