简体   繁体   中英

Store data fetch in a local state redux reactjs

I try to store date of a fetch in local state and not in the global store of my app.

(...)
.then(response => response.json())
.then (data => dispatch(fetchSuccess(data)))

And then:

export const FETCH_SUCCESS = 'FETCH_SUCCESS';
function fetchSuccess(create) {
    return {type : FETCH_SUCCESS, payload: create}
}

I have my data in the reducer with this:

const initialState = {
   eCreate: ''
};
case FETCH_SUCCESS:
      return {...state, eCreate: action.payload}

And after I have my state here in my component:

rEvt : state.redu.eCreate

And I can display with:

console.log(rEvt)

But my state eCreate is available in all my app. I just want that this state was available just in this component. How can i do this? Thanks for help.

My component

function Create(props) {

    const {cEvt, sEvt, gtf, rEvt} = props;

    console.log(rEvt)


    if (rEvt.name === sEvt)
    {
        return <Redirect to={"/d/" + rEvt.name} />
    }


    return (
        <div >
            <input type="text" value={sEvt} onChange={e => cEvt(e.target.value)} />
            <button onClick={() => gtf(sEvt)} >Go !</button>

        </div>
    );
}

And the container of my compo:

const mapStateToProps = (state) => ({
    sEvt : state.redu.sCreate,
    rEvt : state.redu.eCreate
})

const mapDispatchToProps = dispatch => ({
    cEvt : e => dispatch(changeInput(e)),
    gtf : (name) => dispatch(fetchCreate(name))
})

My fetch has a method POST to create a new entry with the name of the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM