Search code examples
javascriptnode.jsreactjsreact-nativeredux-saga

how can i dispatch action right after theother action?


i'm using react native with redux saga

if i press onLike button i want to dispatch LIKE_POST_REQUEST and right after i get LIKE_POST_SUCCESS i want to dispatch LOAD_POST_REQUEST

here is my code

(Explain.js)

    const Explain = ({navigation,route}) => {

       const dispatch = useDispatch();

  const {me} = useSelector((state) =>state.user);
  const {singlePost} = useSelector((state) => state.post);



  const onLike = () => {
    return dispatch({
        type: LIKE_POST_REQUEST,
        data: singlePost?.id,
    }),
    
    dispatch({
        type: LOAD_POST_REQUEST,
        data:singlePost.id
        })
    
    }
    
    
    const onUnlike = () => {
    return dispatch({
        type: UNLIKE_POST_REQUEST,
        data: singlePost?.id,
    }),
    
    dispatch({
        type: LOAD_POST_REQUEST,
        data:singlePost.id
        })
    
    }


  

  const liked = singlePost?.Likers.find((v) => v.id === me?.id);

    return (
<Container>
  <Hi>
      안녕
  </Hi>


  {  liked       
    ?  
    <MenuContainer  onPress={onUnlike}  >
    <IconButtonU iconName="favorite"
        style={{width:23, height:23}}
        source={require('../../Assets/Images/Tabs/heart.png')}
        />
</MenuContainer>
    :   
    <MenuContainer  onPress={onLike}  >
    <IconButtonU iconName="favorite"
        source={require('../../Assets/Images/Tabs/ic_favorite_outline.png')}
        />
        </MenuContainer>
      }


<LikeNumber>
  좋아요{' '}
  {singlePost?.Likers.length }
</LikeNumber>


  

  </Container>

    );
};

export default Explain;

but when i press onLike dispatch action's process irregular

how can i fix my code??

this is dispatch action's process what i want

enter image description here


Solution

  • If you want two actions to be called one after the other, then you first have to wait for the Promise to resolve/reject from the first action. My suggestion is to create one action which internally calls two other actions synchronously. Or you can just call the LOAD_POST_REQUEST action from inside LIKE_POST_REQUEST after the API call has resolved.