Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

103
Views
How to dispatch without connect

I want to dispatch without a component. I made this code:

const handleClient = () => (dispatch) => {
  try {
    dispatch({
      type: "SET_CLIENT",
      user: {
        id: 1,
        name: "client",
      },
    });
  } catch (err) {
    console.log(err);
  }
};
export default handleLogin;

But this code doesn't work. I import this file and use that in onSubmit event. I use Redux-Thunk. @Edit Look at this code from tutorial

export const fetchContacts = () => (dispatch) => {
  fetch("https://myapi.local/contacts)
    .then(res => res.json())
    .then(json => dispatch(contactsFetched(json.results)));
};

I done something similar and it works so I don't understand that in this example it doesn't work. I tryed other method

import actions from "./actions";
import store from "../store";
const handleClient = () =>  {
    try{
        
        store.dispatch(actions.setClient({id: 1, name: 'Hello'}));
    } catch(err){
        console.log(err);
    }
}
export default handleClient;

but it doesn't work too.

7 months ago · Juan Pablo Isaza
2 answers
Answer question

0

https://redux.js.org/api/store#dispatchaction

You need to have access to your instance of the redux store, which you created somewhere in your codebase via createStore(). Then it's just store.dispatch(handleclient()).

Please keep in mind that this is usually a rare requirement and potentially a code smell. Why is your thunk not triggered from within a React component?

7 months ago · Juan Pablo Isaza Report

0

You should never use store.dispatch, so your first example is incorrect. Your second example is better, but the only place where you can use useDispatch is inside a function component or a custom hook, you cannot use it inside a callback like handleLogin. Try to use useDispatch at the beginning of your React component and then pass the dispatch function as an argument to handleLogin.

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.