Home > Mobile >  Can I use multiples useState and set data when api's got success using axios in react js?
Can I use multiples useState and set data when api's got success using axios in react js?

Time:08-06

Can I use multiples useState like this? Actually this code is working but I want to clean it.

const [shareCode, setShareCode] = useState();
const [createdBy, setCreatedBy] = useState();
const [className, setClassName] = useState();
const [subjectName, setSubjectName] = useState();
const [avatar, setAvatar] = useState();
const [startDate, setStartDate] = useState();
const [endDate, setEndDate] = useState();
const [quizStatus, setQuizStatus] = useState();

useEffect(() => {
    commonApiCall(`url${var}`, {}, 'get').then((response) => {
        if (response.status_code == 200) {
            setShareCode(response.response.quiz.share_code)
            setCreatedBy(response.response.quiz.created_by)
            setClassName(response.response.quiz.class_id)
            setSubjectName(response.response.quiz.subject_meta.subject_name)
            setAvatar(response.response.quiz.image_avatar.image_path)
            setStartDate(response.response.quiz.start_date)
            setEndDate(response.response.quiz.end_date)
            setQuizStatus(response.response.quiz.status)
        }
    }).catch((error) => {
        console.log(error)
    })
}, [])

CodePudding user response:

function commonApiCall(url, data, method) {
    const token = localStorage.getItem("token")
    return axios({
        method: method,
        url: url,
        data: data,
        headers: {
            "Authorization": token
        }
    })
}

export default function QuizDetails() {
    return (
        <div>
            <div>{shareCode}</div>
            <div>{createdBy}</div>
            <div>{className}</div>
            <div>{subjectName}</div>
            <div>{avatar}</div>
            <div>{startDate}</div>
            <div>{endDate}</div>
            <div>{quizStatus}</div>
        </div>
    )
}

CodePudding user response:

You can use as much useState hooks as you would like.

May I just suggest to use a useReducer hook for these kinda scenarios. That way you can set multiply states at once.

I can share a great article by ROBIN WIERUCH.

Because the code is to long for a post I will just share the reducer function to prove a point.

  switch (action.type) {
    case 'FETCH_INIT':
      return {
        ...state,
        isLoading: true,
        isError: false
      };
    case 'FETCH_SUCCESS':
      return {
        ...state,
        isLoading: false,
        isError: false,
        data: action.payload,
      };
    case 'FETCH_FAILURE':
      return {
        ...state,
        isLoading: false,
        isError: true,
      };
    default:
      throw new Error();
  }
};

As you can see multiple properties in a state are set by just dispatching one action.

  • Related