How to make a Dispatch with the variable type in React with useContext

Asked

Viewed 16 times

0

I’m passing a file made in Mobx to Contextapi, but Mobx is in class mode and the initial states are like this:

@observable nomeFantasia = ''
@observable cnpj = ''
@observable inscEstadual = ''
@observable inscMunicipal = ''
@observable telefone = ''
@observable celular = ''
@observable rua = ''
@observable numero = ''
@observable bairro = ''
@observable cidade = ''
@observable uf = ''
@observable complemento = ''

And the function to change states is this way:

@action onChange = e => {
    const {
      target: { name, value }
    } = e
    this[name] = value
  }

What I want to do is exactly that but with useContext using Dispatch (useReducer), my initial hoock state:

  cnpj: '',
  inscEstadual: '',
  inscMunicipal: '',
  telefone: '',
  celular: '',
  rua: '',
  numero: '',
  bairro: '',
  cidade: '',
  uf: '',

The Ref is like this:

const reducer = (state, action) => {
  switch (action.type) {
    case action.type.SET_RAZAO_SOCIAL:
      return { ...state, razaoSocial: action.payload }
    case action.type.SET_NOME_FANTASIA:
      return { ...state, nomeFantasia: action.payload }
    case action.type.SET_CNPJ:
      return { ...state, cnpj: action.payload }
    case action.type.SET_INSCRICAO_ESTADUAL:
      return { ...state, inscEstadual: action.payload }
    case action.type.SET_INSCRICAO_MUNICIPAL:
      return { ...state, inscMunicipal: action.payload }
    case action.type.SET_TELEFONE:
      return { ...state, telefone: action.payload }
    case action.type.SET_CELULAR:
      return { ...state, celular: action.payload }
    case action.type.SET_RUA:
      return { ...state, rua: action.payload }
  }
}

Where I’m in doubt is in Dispatch how to do it I don’t know how to type: SET_..., like this:

const mudar = e => {
    const {
      target: { name, value }
    } = e
    dispatch({ type: ???, payload: value })
}

In the case "name" is the initial state type:

'cnpj'

Or

'telefone'

Needed to link name to type type:

SET_CNPJ

Or

SET_TELEFONE

Someone can help me?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.