2

I'm struggling with how to fetch data using RxJS and axios onClick in a React component. But getting closer, I think. Any attempts I've tried either run when component mounts, not onClick, or don't run at all even onClick.

Basically, how to call onClick and how to pass a payload. There just seems to be nothing online to explain this which i would expect to be a common situation.

const MyComponent = () => {
  const [data, setData] = useState(null);

  const getData$ = new Subject(observer => {
    axios
      .post(`/my-url/`, **how to get payload to here**)
      .then(response => {
        observer.next(response.data);
        observer.complete();
      })
      .catch(error => {
        observer.error(error);
      });
  });

  useEffect(() => {
    const subs = getData$.subscribe({
      next: res => setData(res),
    });
    return () => subs.unsubscribe();
  }, []);

  return (
    <Button onClick={() => getData$.next(payload)} />
  );
};

Any help appreciated.

1 Answer 1

2

you can pass in the payload in getData like this

const getData$ = (payload) => new Subject(observer => {
    axios.post(`/my-url/`, payload)
        .then(response => {
            observer.next(response.data);
            observer.complete();
        })
        .catch(error => {
            observer.error(error);
        });
});

This basically just creates an anonymous function called getData that returns your Subject. It's equivalent to this:

const getData$ = function (payload) {
    return new Subject(observer => {
        axios.post(`/my-url/`, payload)
            .then(response => {
                observer.next(response.data);
                observer.complete();
            })
            .catch(error => {
                observer.error(error);
            });
    });
};
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. So by turning it into a function means it won't be called immediately? And am I calling getData$ the correct way? () => getData$.next(payload)
I can't subscribe to getData$ now since turning it into a function. Seems like there must be another solution. Thank you though
Have you resolved this issue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.