Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

JavaScript Patch Http request is not working

theNewbie

New Coder
I've been trying to use the http requests to update a status of a car, so that it will for example go from 'pending' to 'canceled'. I am using patch because I do not want to update all data but only statusId.

But what is strange, is that it deletes the car, and I do not get any errors. Why, as I know patch updates partial data, and shouldn't delete? It has connection to my api since it deletes the data from the database too.

I also have a website, where I have admin panel, and it is working there, no problem with the backend API.

JavaScript:
useEffect(() => {
     const getToken = async () => {
            const as = useSecureStorage('AccessToken');
            const token = await as.getItem();
            setToken(token || '');
            setLoadingProcess(false);
    };
    getToken();
}, []);

const handleCancelCar = async () => {
        try {
            setSubmitting(true);
            const as = await asStorage.getItem();
            const app = await client.tokenClient();
            const updateDto: UpdateStatus = {
                statusId: 989,
            };

            const response = await app!.patch(
                `/car/${id}/status/`,
                updateDto,
            );

            if (response.status === 200) {
                console.log('Updated car status');
            } else {
                console.log('Failed to update car status');
            }
        } catch (error) {
            console.log({ error });
        }
    };

Here's how my button is implemented:

JavaScript:
<Button
                        backgroundColor={Colors.red40}
                        source={{
                            uri: uri + '',
                            headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json',
                                Authorization: token ? `Bearer ${token}` : '',
                            },
                        }}
                            onPress={handleCancelCar}
                    >
                        <TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center' }}>
                            <Text text65 white style={{ fontWeight: '700', marginLeft: 10 }}>
                                {t('Cancel Car')}
                            </Text>
                        </TouchableOpacity>
                    </Button>

I am not getting any errors, it just deletes my car.
Any ideas?
 
I've been trying to use the http requests to update a status of a car, so that it will for example go from 'pending' to 'canceled'. I am using patch because I do not want to update all data but only statusId.

But what is strange, is that it deletes the car, and I do not get any errors. Why, as I know patch updates partial data, and shouldn't delete? It has connection to my api since it deletes the data from the database too.

I also have a website, where I have admin panel, and it is working there, no problem with the backend API.

JavaScript:
useEffect(() => {
     const getToken = async () => {
            const as = useSecureStorage('AccessToken');
            const token = await as.getItem();
            setToken(token || '');
            setLoadingProcess(false);
    };
    getToken();
}, []);

const handleCancelCar = async () => {
        try {
            setSubmitting(true);
            const as = await asStorage.getItem();
            const app = await client.tokenClient();
            const updateDto: UpdateStatus = {
                statusId: 989,
            };

            const response = await app!.patch(
                `/car/${id}/status/`,
                updateDto,
            );

            if (response.status === 200) {
                console.log('Updated car status');
            } else {
                console.log('Failed to update car status');
            }
        } catch (error) {
            console.log({ error });
        }
    };

Here's how my button is implemented:

JavaScript:
<Button
                        backgroundColor={Colors.red40}
                        source={{
                            uri: uri + '',
                            headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json',
                                Authorization: token ? `Bearer ${token}` : '',
                            },
                        }}
                            onPress={handleCancelCar}
                    >
                        <TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center' }}>
                            <Text text65 white style={{ fontWeight: '700', marginLeft: 10 }}>
                                {t('Cancel Car')}
                            </Text>
                        </TouchableOpacity>
                    </Button>

I am not getting any errors, it just deletes my car.
Any ideas?
Hi there,
A PATCH request doesn't necessarily delete a record from the db unless the database was set up to do so under certain conditions. How is the db set up?
 
Last edited:
Hi there,
A PATCH request necessarily delete a record from the db unless the database was set up to do so under certain conditions. How is the db set up?
SQL:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  ALTER VIEW [dbo].[vCarListView]
  AS
  SELECT T.Id, T.Title, T.Content, COALESCE(A.FullName, T.[Location]) AS 'Location', T.StartTime, T.EndTime, DT.[Name] + ' ' + DT.Surname AS 'DelegatedToName',
  DF.[Name] + ' ' + DF.Surname AS 'DelegatedFromName', T.DelegatedFrom, T.DelegatedTo, T.DepartmentId, T.CarTypeId, T.StatusId, COALESCE(T.ChangedDate, T.CreateDate) AS LastEditedDate,
  A.Id AS ApartmentId
  FROM Car T
  LEFT JOIN UserProfile DT on DT.Id = T.DelegatedTo
  LEFT JOIN UserProfile DF on DF.Id = T.DelegatedFrom
  WHERE T.StatusId != 1056
GO

This is the only I have setup. How would I set the Patch request up?
 
SQL:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  ALTER VIEW [dbo].[vCarListView]
  AS
  SELECT T.Id, T.Title, T.Content, COALESCE(A.FullName, T.[Location]) AS 'Location', T.StartTime, T.EndTime, DT.[Name] + ' ' + DT.Surname AS 'DelegatedToName',
  DF.[Name] + ' ' + DF.Surname AS 'DelegatedFromName', T.DelegatedFrom, T.DelegatedTo, T.DepartmentId, T.CarTypeId, T.StatusId, COALESCE(T.ChangedDate, T.CreateDate) AS LastEditedDate,
  A.Id AS ApartmentId
  FROM Car T
  LEFT JOIN UserProfile DT on DT.Id = T.DelegatedTo
  LEFT JOIN UserProfile DF on DF.Id = T.DelegatedFrom
  WHERE T.StatusId != 1056
GO

This is the only I have setup. How would I set the Patch request up?
Sorry, I had a typo in my previous statement, (doesn't necessarily). What I was asking for is to know if the database is set up to cascade on update, or if its set up to where the record gets removed if the record is updated under a "cancelled/closed" status
 
Sorry, I had a typo in my previous statement, (doesn't necessarily). What I was asking for is to know if the database is set up to cascade on update, or if its set up to where the record gets removed if the record is updated under a "cancelled/closed" status
Also... you're not updating anything with that query. Not sure if that was your intention with it or not, but you are just selecting a record with it... To update, you would have to use UPDATE in the query
 
Also... you're not updating anything with that query. Not sure if that was your intention with it or not, but you are just selecting a record with it... To update, you would have to use UPDATE in the query
Thanks, but the thing that confuses me is that, it is possible to update the statuscode through the web-app. Do it have something with the api, that it handles it other way, in a different way?
 
Thanks, but the thing that confuses me is that, it is possible to update the statuscode through the web-app. Do it have something with the api, that it handles it other way, in a different way?
So, as far as updating the record through the web-app itself, I would strongly advice against that, for security purposes. Creating an API would be a better solution, yes, it does mean a bit more work, but worth it. Of course, you would still have write the code to handle the update in the database when the PATCH request is made
 
So, as far as updating the record through the web-app itself, I would strongly advice against that, for security purposes. Creating an API would be a better solution, yes, it does mean a bit more work, but worth it. Of course, you would still have write the code to handle the update in the database when the PATCH request is made
Thanks for the advice, did it as you described. It is working now 🙂
 

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom