Tapiwa Kundishora
Tapiwa Kundishora

Reputation: 19

How do I pass state into my action creator

I wanted to know how I can pass the state into an action so that it can use the state to make an API call. the state I want to pass is the input because it's the image URL that gets sent to Clarifai's servers to predict the celebrity. The handle search is responsible for updating state to the URL.

I've tried to use get state with no luck

This is my action

export const requestPrediction = () => {
  return function (dispatch, getState) {
    dispatch(fetchCelebrequest)
    let input = getState().input 
    app.models.predict(Clarifai.CELEBRITY_MODEL,
      input)
      .then(res => {
        const data = res.outputs[0]['data']['regions'][0]['data'].concepts[0]
        dispatch(fetchCelebSuccess(data))
      })
      .catch(err => {
        const error = err.message
        dispatch(fetchCelebFailed(error))
      })
  }
}

This is my reducer.js

import { 
    CHANGE_SEARCHFIELD,
    REQUEST_PREDICTION_PENDING,
    REQUEST_PREDICTION_SUCESS,
    REQUEST_PREDICTION_FAILED
} from './constants'


const initialState = {
    input: '',
    imageUrl: '',
    box: {},
    isSignedIn: false,
    isPending: false,
    celeb: {},
    error: '',
    celebConfidence: [],
    user: {
    id: '',
    name: '',
    email: '',
    entries: 0,
    joined: ''
    }
}

export const handleSearch = (state=initialState, action={}) => {
    switch (action.type) {
        case CHANGE_SEARCHFIELD:
            return { ...state, input: action.payload }
        default:
            return state
    }
}

export const requestPrediction = (state=initialState, action={}) => {
    switch(action.type) {
        case REQUEST_PREDICTION_PENDING:
            return {...state, isPending: true}
        case REQUEST_PREDICTION_SUCESS:
            return {...state, celebName: action.payload, isPending: false}
        case REQUEST_PREDICTION_FAILED:
            return {...state, error: action.payload, isPending: false}
        default:
            return state
    }
}

Upvotes: 0

Views: 63

Answers (1)

CyberMessiah
CyberMessiah

Reputation: 1268

The proper way to do it is via setState since the updates my be asynchronous. You may check out this link. How can I pass state to an action in React.js?

Upvotes: 1

Related Questions