Oh… Now I can see what you are trying to do. Actually the solution you have written looks correct to me for given image.I would suggest one error safe approach to try.
src={photo.attributes?.file?.data?.attributes?.formats?.medium?.url || ‘’}
Also did you check if there are multiple images in your response photos object and any other image has missing formats property.