User submits with inconsistent behaviour

Website: map.hoopers.club

Hi, there. I am having some inconsistent behaviour when users submit data through my form.

Sometimes it works just fine, but sometimes I get submission alert, but nothing is pushed to github. Or no submission at all.

It’s been very difficult to recreate these behaviours hence being so hard for me to understand what may be the problem.

This is my FormSubmit.jsx:

import { useState, useCallback } from 'react';
import { useDropzone } from 'react-dropzone';
import axios from 'axios';


const addData = (object) => {
	let date = new Date().toUTCString().replace(/[\s|,|:]/g, "-");
	console.log('function added object',object);

	let objects = 
		`---
		name: Automatic-file-${date}
		location:
		lat: ${object?.latitude ? object?.latitude : ''}
		lng: ${object?.longitude ? object?.longitude : ''}
		email: ${object?.email ? object?.email : ''}
		byhoopers: ${object?.byhoopers ? object?.byhoopers : false}
		openUse: ${object?.openUse}
		openTime: ${object?.openTime ? object?.openTime : "unknown"}
		social: ${object?.social ? object?.social : ''}
		image: ${object?.file?.url}
		formcourt: true
		---
		${object?.info ? object?.info : ""}
		![](${object?.file2?.url ? object?.file2?.url : ""})
		![](${object?.file3?.url ? object?.file3?.url : ""})
		![](${object?.file4?.url ? object?.file4?.url : ""})
		![](${object?.file5?.url ? object?.file5?.url : ""})
		`;
  
	


	let fix = btoa(objects);
	var info = JSON.stringify({
		message: `new court file ${date}`,
		content: fix,
	});
  
	var config = {
	  	method: "put",
	  	url: `https://api.github.com/repos/hoopersclub/hoopersmap/contents/content/${
			date
		}.md`,
	  	headers: {
			Authorization: "*************************************",
			"Content-Type": "application/json",
	  	},
	  	data: info,
	};
	
	axios(config)
		.then(function (response) {
			console.log(JSON.stringify(response.data));
	  	})
	  	
		.catch(function (error) {
			console.log(error);
	  	});
	
	return {
	  	statusCode: 200,
		body: 'submited form',
	};
};
  

const FormSubmit = ({ animation, handleNext, handlePrev, court }) => {
	const [name, setName] = useState('');
	const [status, setStatus] = useState('');
	const [email, setEmail] = useState('');
	const [message, setMessage] = useState('');
	const [file, setFile] = useState({});
	const [file2, setFile2] = useState({});
	const [file3, setFile3] = useState({});
	const [file4, setFile4] = useState({});
	const [file5, setFile5] = useState({});
	const [social, setSocial] = useState('');
	const [openTime, setOpenTime] = useState('');
	const [openUse, setOpenUse] = useState("Not-Free");
	const [info, setInfo] = useState('');
	const [imagesrc, setImagesrc] = useState('/assets/noun_Upload_3927082.svg');
 
	const onDrop = useCallback((acceptedFiles) => {
		// console.log(acceptedFiles[0]);
		if (acceptedFiles[0]) setFile(acceptedFiles[0]);
		if (acceptedFiles[1]) setFile2(acceptedFiles[1]);
		if (acceptedFiles[2]) setFile3(acceptedFiles[2]);
		if (acceptedFiles[3]) setFile4(acceptedFiles[3]);
		if (acceptedFiles[4]) setFile5(acceptedFiles[4]);

		setImagesrc('/assets/photo.png');
	}, []);
	
	const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

	const encode = (data) => {
		const formData = new FormData();
		Object.keys(data).forEach((k) => {
			formData.append(k, data[k]);
		});

		return formData;
	};

	const handleSubmit = (e) => {
		const data = {
			'form-name': 'contact',
			name,
			email,
			message,
			file,
			file2,
			file3,
			file4,
			file5,
			social,
			openTime,
			openUse,
			info,
			latitude: court?.lat,
			longitude: court?.lng,
		};

		fetch('/', {
			method: 'POST',
			// headers: { "Content-Type": 'multipart/form-data; boundary=random' },
			body: encode(data),
		})
		.then(() => {
			setStatus('Form Submission Successful!!');
			fetch('/.netlify/functions/getform').then((response) => response.json()).then((data) => addData(data));
		})
		.catch((error) => setStatus('Form Submission Failed!'));

		e.preventDefault();
		
		handleNext();
	};


	const handleChange = (e) => {
		const { name, value } = e.target;
		if (name === 'name') {
			return setName(value);
		}
		if (name === 'message') {
			return setMessage(value);
		}
		if (name === 'email') {
			return setEmail(value);
		}
		if (name === 'social') {
			return setSocial(value);
		}
		if (name === 'openTime') {
			return setOpenTime(value);
		}
		if (name === 'info') {
			return setInfo(value);
		}
		if (name === 'openUse') {
			if (openUse === "Not-Free") {
				setOpenUse("Free");
			} else {
				setOpenUse("Not-Free");
			}
		}
	};

	return (
		<div className='box'>
			<div className={`content ${animation ? 'next-pane' : ''}`}>
				<div className='title'>UPLOAD IMAGES*</div>
				<form className='form' onSubmit={handleSubmit} action='/thank-you/'>
					<div className='upload' {...getRootProps()}>
						<input {...getInputProps()} />
						{isDragActive ? (
							<p>Drop the files here ...</p>
						) : (
							<p>
								<img src={imagesrc} alt='' />
								Click to select, or drag and drop the basketball court pictures
							</p>
						)}
					</div>
					<div className='form-details'>
						<div className='form-left'>
							<div className='form-info'>
								<label htmlFor='email'>Email*</label>
								<input
									type='email'
									name='email'
									placeholder='Your email address'
									value={email}
									onChange={handleChange}
									required
								/>
							</div>
							<div className='form-info'>
								<label htmlFor=''>Instagram</label>
								<input
									required
									type='text'
									name='social'
									placeholder='Your Instagram handle'
									value={social}
									onChange={handleChange}
								/>
							</div>
							<div className='form-info'>
								<label htmlFor='required'>Game time</label>
								<input
									required
									type='text'
									name='openTime'
									placeholder='Do you know when the court is open?'
									value={openTime}
									onChange={handleChange}
								/>
							</div>
						</div>
						<div className='form-right'>
							<div className='form-info inline '>
								<label htmlFor='openUse' className='column'>
									Is this court free to use?
								</label>
								<input
									className='form-checkbox'
									type='checkbox'
									name='openUse'
									value={openUse}
									onChange={handleChange}
								/>
							</div>
							<div className='form-info'>
								<label htmlFor='info'>More info about this court</label>
								<textarea
									name='info'
									id='info'
									cols='30'
									rows='5'
									placeholder='Is there any other information about this court that people might find useful?'
									value={info}
									onChange={handleChange}></textarea>
							</div>
						</div>
					</div>
					<p>
						<button
							type='submit'
							className='btn centered'>
							SEND COURT TO REVIEW
						</button>
					</p>
				</form>
				<h3>{status}</h3>
				<div className='content-progress'>
					<img
						src='/assets/search/esquerda_habilitada.svg'
						alt=''
						className='left '
						onClick={() => handlePrev()}
					/>
					<div className='step title'>
						<div className='top'>STEP</div> <br />
						<div className='bottom'>2/2</div>
					</div>
					<img
						// onClick={() => handleNext()}
						src='/assets/search/direita_desabilitada .svg'
						alt=''
						className='right '
					/>
				</div>
			</div>
		</div>
	);
};

export default FormSubmit;

I’m thinking it might be something to do with assyncronous functions that is causing such inconsistencies.

Hoepfully someone can help out and catch something I might be missing.
Thanks.

Are there any errors in your Netlify Function logs?

Sorry for the dumb newbie question. Where/how can I find function logs?

In your Netlify dashboard, within the sites dashboard, there’s a function tab, with logs for each function: https://app.netlify.com/sites/{{site-name}}/functions/{{function-name}}.

I submited a new test form and got the following log error:

Apr 6, 02:16:20 PM: 0fc7970b ERROR  Invoke Error 	{"message":"Request failed with status code 400","name":"Error","stack":"Error: Request failed with status code 400\n    at createError (/var/task/node_modules/axios/lib/core/createError.js:16:15)\n    at settle (/var/task/node_modules/axios/lib/core/settle.js:17:12)\n    at IncomingMessage.handleStreamEnd (/var/task/node_modules/axios/lib/adapters/http.js:293:11)\n    at IncomingMessage.emit (events.js:412:35)\n    at endReadableNT (internal/streams/readable.js:1334:12)\n    at processTicksAndRejections (internal/process/task_queues.js:82:21)","config":{"transitional":{"silentJSONParsing":true,"forcedJSONParsing":true,"clarifyTimeoutError":false},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"maxBodyLength":-1,"headers":{"Accept":"application/json, text/plain, */*","User-Agent":"axios/0.22.0"},"method":"get","url":"https://v1.nocodeapi.com/hoopersinfo/netlify/sopVnsAfFGcoqkeU/listFormSubmissions?form_id=616b235535ee36000787161f","params":{}},"status":400}

The submission form was received on netlify. Nothing on github.

My getform.js:

const axios = require("axios");
// const axios2 = require("axios");
exports.handler = async function (event, context) {
  return axios({
    method: "get",
    url: "https://v1.nocodeapi.com/hoopersinfo/netlify/sopVnsAfFGcoqkeU/listFormSubmissions?form_id=616b235535ee36000787161f",
    params: {},
  }).then(({ data }) => {
    let object = data[0].data;
    return {
      statusCode: 200,
      body: JSON.stringify(object),
    };
  });
};

Your API is responding with a bad request code, apparently.

yeah. Can’t figure why :thinking:

So I removed the following validation:

lat: ${object?.latitude ? object?.latitude : ''}
lng: ${object?.longitude ? object?.longitude : ''}

I don’t get the log error no more. Instead I’m saving md files to github with undefined data.

I’m not being able to get the data from form’s submissions.

I refactored my code.

I am now using submission-created.js Netlify’s trigger on form submit.

My submission-created file looks like:

const axios = require('axios');

exports.handler = async function(event, context, callback) {
  
    const data = JSON.parse(event.body).payload.data;
    
    let date = new Date().toUTCString().replace(/[\s|,|:]/g, "-");
    date = date.substring(5, date.length);

    let courtData = 
`---
name: Automatic-file-${date}
location:
lat: ${data?.latitude}
lng: ${data?.longitude }
email: ${data?.email}
byhoopers: ${data?.byhoopers ? data?.byhoopers : false}
openUse: ${data?.openUse}
openTime: ${data?.openTime ? data?.openTime : "unknown"}
social: ${data?.social}
image: ${data?.file?.url}
formcourt: true
---
${data?.info ? data?.info : ""}
![](${data?.file2?.url ? data?.file2?.url : ""})
![](${data?.file3?.url ? data?.file3?.url : ""})
![](${data?.file4?.url ? data?.file4?.url : ""})
![](${data?.file5?.url ? data?.file5?.url : ""})
`;

    let githubContent = Buffer.from(courtData).toString('base64');

    let courtInfo = JSON.stringify({
        message: `new court file ${date}`,
        content: githubContent,
    });
    
    let githubPush = {
        method: "put",
        url: `https://api.github.com/repos/hoopersclub/hoopersmap/contents/content/${date}.md`,
        headers: {
            Authorization: "********",
            "Content-Type": "application/json",
        },
        data: courtInfo,
    };

    axios(githubPush)
      .then(function (response) {
        console.log(JSON.stringify(response.data));
    })
      .catch(function (error) {
        console.log(error);
    });

    return { 
        statusCode: 200,
        body: JSON.stringify(data),
    };
};

If I submit a form locally it is creating the md file on github with the data.
But in production it’s not creating the md file. Submission is received but it doesn’t seem to trigger submission-created

Try changing this part of your code:

return axios(githubPush)
      .then(function (response) {
        console.log(JSON.stringify(response.data));
       return { 
        statusCode: 200,
        body: JSON.stringify(data),
      };
    })
      .catch(function (error) {
        console.log(error);
    });

   

Hi, @hrishikesh

Thanks for your solution. I was able to make it work on friday with await axios.

Sorry for not posting it here, I was kind of in a rush :sweat_smile:

1 Like