Where to make the API request for `WIDGET_UPDATE` action?
n-ii-ma opened this issue · comments
I was wondering about how I can make an API request to update the widget and was confused about where to make the request.
Do I have to make the API request inside the case of WIDGET_UPDATE
action like this:
switch (props.widgetAction) {
case "WIDGET_UPDATE":
const response = await axios.get('https://example.com/api');
const data = response.data;
props.renderWidget(<Widget data={data} />);
break;
default:
break;
}
};
Or can I make it inside the widget-task-handler
and outside the switch cases like this:
const widgetTaskHandler = async (props: WidgetTaskHandlerProps) => {
const widgetInfo = props.widgetInfo;
const Widget =
nameToWidget[widgetInfo.widgetName as keyof typeof nameToWidget];
const response = await axios.get('https://example.com/api');
const data = response.data;
switch (props.widgetAction) {
case "WIDGET_UPDATE":
props.renderWidget(<Widget data={data} />);
break;
default:
break;
}
};
It seems the second method works as well and would be much more suitable for situations where the data fetching also happens upon the WIDGET_ADDED
action.
const response = await axios.get('https://example.com/api');
const data = response.data;
switch (props.widgetAction) {
case "WIDGET_ADDED":
case "WIDGET_UPDATE":
props.renderWidget(<Widget data={data} />);
break;
default:
break;
}
Whatever works best for you, there is no such limitation from the library.
Your approach seems fine.
Keep in mind you probably do not want to fetch the data if the user removes the widget (WIDGET_DELETED
action).
Whatever works best for you, there is no such limitation from the library.
Your approach seems fine. Keep in mind you probably do not want to fetch the data if the user removes the widget (
WIDGET_DELETED
action).
Oh, so I indeed should use the first method and fetch the data in the WIDGET_ADDED
and WIDGET_UPDATE
action cases since by using the second method, the data would be fetched on other actions like WIDGET_DELETED
and WIDGET_RESIZED
even if it's not being passed as a prop in those render cases.
I hope I understood your note correctly.
Or you could do
switch (props.widgetAction) {
case "WIDGET_ADDED":
case "WIDGET_UPDATE":
const response = await axios.get('https://example.com/api');
const data = response.data;
props.renderWidget(<Widget data={data} />);
break;
default:
break;
}
You also don't need to use a switch
statement, it was used in the examples because it looked cleaner to show all the options.